User2012384 User2012384 - 1 year ago 129
Android Question

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 */);

String queryString = getQuery(dataToPost);
OutputStream os = conn.getOutputStream();
int response = conn.getResponseCode();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
is = conn.getInputStream();
contentAsString = convertInputStreamToString(is, length);
} catch (MalformedURLException e) {
} catch (UnsupportedEncodingException e) {
} catch (ProtocolException e) {
} catch (IOException e) {
String k = e.getMessage();
} finally {
if (is != null) {
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;

result.append(URLEncoder.encode(key, "UTF-8"));
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];;
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

And I made an 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? failed to connection to localhost/
(port 59524) after 15000ms: ECONNREFUSED (Connection refused)

The above IOException throws in

Expected result:

When I post the "ID" to
, I
should receive a string "Very good!"

Answer Source

use Soap webservice to call the web service.

My 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 = "";

    //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 = "";

    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

        // Set Value

        // Set dataType

        // Add the property to request object

        SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
        envelope.dotNet = true;

        // Set output SOAP object

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

        try {
            // Invoke web service
  , 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;

        //Return booleam to calling object
        return loginStatus;

My asynchtask class

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

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

    protected void onPreExecute() {



My webservice code

[WebService(Namespace = "")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]

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


feel free to comment here