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:

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!"
ipconfigin console if you have windows, under "IPv4 address".