User2012384
User2012384

Reputation: 4919

Java HttpURLConnection failed to connect to ASP.NET API, connection refused

I am trying to use below code to post some data in Java (In Android Studio):

public static String downloadContent(URL url, ContentValues dataToPost) throws IOException {
    InputStream is = null;
    int length = 500;
    String contentAsString = "";

    try {
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setReadTimeout(10000 /* milliseconds */);
        conn.setConnectTimeout(15000 /* milliseconds */);
        conn.setRequestMethod("GET");
        conn.setDoInput(true);

        String queryString = getQuery(dataToPost);
        conn.connect();
        OutputStream os = conn.getOutputStream();
        int response = conn.getResponseCode();
        BufferedWriter writer = new BufferedWriter(
                new OutputStreamWriter(os, "UTF-8"));
        writer.write(queryString);
        writer.flush();
        writer.close();
        is = conn.getInputStream();
        contentAsString = convertInputStreamToString(is, length);
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ProtocolException e) {
        e.printStackTrace();
        e.printStackTrace();
    } catch (IOException e) {
        String k = e.getMessage();
    } finally {
        if (is != null) {
            is.close();
        }
    }
    return contentAsString;
}

private static String getQuery(ContentValues params) throws UnsupportedEncodingException {
    StringBuilder result = new StringBuilder();
    boolean first = true;

    for (String key : params.keySet()) {
        if (first)
            first = false;
        else
            result.append("&");

        result.append(URLEncoder.encode(key, "UTF-8"));
        result.append("=");
        result.append(URLEncoder.encode(params.get(key).toString(), "UTF-8"));
    }

    return result.toString();
}

public static String convertInputStreamToString(InputStream stream, int length) throws IOException, UnsupportedEncodingException {
    Reader reader = null;
    reader = new InputStreamReader(stream, "UTF-8");
    char[] buffer = new char[length];
    reader.read(buffer);
    return new String(buffer);
}

And I'm calling the downloadContent method using below code:

URL u = new URL("http://localhost:59524/api/Test/AAA?id=1");
                ContentValues c = new ContentValues();
                c.put("id", "1");
                NetworkCommunication.downloadContent(u, c);

I've also tried changing the URL to http://localhost:59524/api/Test/AAA

And I made an asp.net MVC API using C# (In visual studio) for testing, and here's the code for the API:

public class TestController : ApiController
{
    [AcceptVerbs("GET", "POST")]
    public IHttpActionResult AAA(int id)
    {
        return Ok("Very good!");
    }
}

I am able to access the API through the browser: enter image description here

But why in android studio, the program failed to connect?

java.net.ConnectException: failed to connection to localhost/127.0.0.1 (port 59524) after 15000ms: ECONNREFUSED (Connection refused)

The above IOException throws in conn.connect();

Expected result:

When I post the "ID" to http://localhost:59524/api/Test/AAA, I should receive a string "Very good!"

Upvotes: 0

Views: 1358

Answers (1)

Yogesh Nikam
Yogesh Nikam

Reputation: 633

use Soap webservice to call the asp.net web service.

My WebSrevice.java class code

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.PropertyInfo;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import android.R.array;
import android.util.Log;

public class WebService {
    //Namespace of the Webservice - can be found in WSDL
    private static String NAMESPACE = "http://tempuri.org/";

    //Webservice URL - WSDL File location   
    private static String URL = "webservice path";

    //Make sure you changed IP address
    //SOAP Action URI again Namespace + Web method name
    private static String SOAP_ACTION = "http://tempuri.org/";

    public static String invokeCategory( String webMethName, String compId) {
        String loginStatus = "";

        // Create request
        SoapObject request = new SoapObject(NAMESPACE, webMethName);

        // Property which holds input parameters
        PropertyInfo compidPI = new PropertyInfo();

        // Set Username
        compidPI.setName("companyid");

        // Set Value
        compidPI.setValue(compId);

        // Set dataType
        compidPI.setType(String.class);

        // Add the property to request object
        request.addProperty(compidPI);

        SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
            SoapEnvelope.VER11);
        envelope.dotNet = true;

        // Set output SOAP object
        envelope.setOutputSoapObject(request);

        // Create HTTP call object
        HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);

        try {
            // Invoke web service
            androidHttpTransport.call(SOAP_ACTION+webMethName, envelope);

            // Get the response
            SoapPrimitive response = (SoapPrimitive) envelope.getResponse();

            // Assign it to  boolean variable variable
            loginStatus = response.toString();

        } catch (Exception e) {
            //Assign Error Status true in static variable 'errored'
            Login.errored = true;
            e.printStackTrace();
        } 

        //Return booleam to calling object
        return loginStatus;
    } 
}

My asynchtask class

private class GetCategoryAndProduct extends AsyncTask<String,Void,Void>  
{
    @Override
    protected Void doInBackground(String... params) {
        //Call Web Method
        data =(WebService.invokeCategory("getCategory",company_id,"0"));
        return null;
    }

    @Override
    //Once WebService returns response
    protected void onPostExecute(Void result) {
        //get server response here

        }
        }
    }
    @Override
    protected void onPreExecute() {

    }

}

My Asp.net webservice code

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]

public class Login_Service : System.Web.Services.WebService
{   
     [WebMethod]
     public string getCategory(string companyid)
     {
        //write your web service code here

     }
 }

feel free to comment here

Upvotes: 1

Related Questions