I get java socket is closed exception meanwhile I am trying to read the response that I got from my web service. My web service sends a JSON as a response and the http code response is always 200 but I do not know if the response String is so long that BufferedReader crash when I try to use readLine(). If the issue is my response size, there is another way to get my json response?
I already used postman to be secured that my web service is working without problems, so I get my json responde as I want.
I use this same format of code to call other web services that I have and I do not have this issue. And actually, this code worked well before, since yesterday that I have this problem.
The error arises in the while below
try {
url = new URL(ws);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "application/json");
//HEADERS
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("Accept", "application/json");
connection.setRequestProperty("User-Agent", "Mozilla/5.0" + " (Linux; Android 1.5; es-ES) Ejemplo HTTP");
connection.connect();
OutputStream outputStream = connection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, StandardCharsets.UTF_8));
bufferedWriter.write(jsonObject.toString());
bufferedWriter.flush();
bufferedWriter.close();
int response = connection.getResponseCode();
connection.disconnect();
StringBuilder result = new StringBuilder();
if (response == HttpURLConnection.HTTP_OK) {
InputStream input = new BufferedInputStream(connection.getInputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
if (!result.toString().equals("null")) {
JSONArray jsonResult = new JSONArray(result.toString());
if (jsonResult.length() > 0) {
//code to use JSON response info
} else {
//code to show alert dialog error
}
} else {
//code to show alert dialog error
}
} else {
//code to show alert dialog error
}
} catch (Exception e) {
Log.i("JSONWSResponse error: ", e.toString());
//code to show alert dialog error
}
Related
I am trying to read the response body for an error response(404,400,500) using java application and basic http client. When testing in my local , I am able to get the proper json response. But when I deployed to azure I am getting the error response body in HTML tags.
Error response I got when deployed to azure and testing from there:
400 Error400 error while attempting to access resource
#AddLoggerInAppInsights
public Map exchangeNativeHttpRequest(String url, String jsonPayLoad, String correlationId) {
Map<String,Object> responseMap = null;
try {
URL httpUrl = new URL(url);
HttpURLConnection conn = (HttpURLConnection) httpUrl.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("Accept", "application/json");
conn.setRequestProperty(CLIENT_ID_KEY, System.getenv(CLIENT_ID_VALUE));
conn.setRequestProperty(CLIENT_SECRET_KEY, System.getenv(CLIENT_SECRET_VALUE));
conn.setRequestProperty(CORRELATION_ID, correlationId);
OutputStream os = conn.getOutputStream();
os.write(jsonPayLoad.getBytes());
os.flush();
HttpStatus httpStatus = HttpStatus.valueOf(conn.getResponseCode());
BufferedReader br = null;
if (conn.getResponseCode() == org.apache.http.HttpStatus.SC_OK) {
br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
}else if (conn.getResponseCode() == org.apache.http.HttpStatus.SC_BAD_REQUEST){
br = new BufferedReader(new InputStreamReader(
(conn.getErrorStream())));
}else {
throw new RuntimeException("Failed : HTTP error code : "
+ conn.getResponseCode());
}
String output;
StringBuilder sb = new StringBuilder();
while ((output = br.readLine()) != null) {
sb.append(output);
}
telemetryClient.trackEvent(correlationId+":" +"Response for Create Breakdown IBMI API from HTTP_CONNECTION: "+sb.toString());
responseMap = new HashMap<>();
responseMap.put("statusCode",httpStatus);
responseMap.put("response", sb.toString());
conn.disconnect();
} catch (MalformedURLException e) {
telemetryClient.trackException(e);
} catch (IOException e) {
telemetryClient.trackException(e);
}
telemetryClient.trackEvent(correlationId+":" +"Returned Response of Create Breakdown IBMI API from HTTP_CLIENT: "+responseMap.toString());
return responseMap;
}
I'm getting a 'Server returned HTTP response code: 500' error although I have checked what I'm sending (I even tried sending it with an online tool and it worked). The API Key and the JSON are correct. I get this error when trying to read the input stream with 'connection.getInputStream()'. Where could this be comming frome ? Did I forget something ? I am trying to implement this feature from the openrouteservice API : https://openrouteservice.org/dev/#/api-docs/v2/directions/{profile}/post
public static UPSRoute getRoute(Location start, Location end, String language) {
if (language.equals("fr")) {
JSONObject jsonObject = null;
try {
URL url = new URL("https://api.openrouteservice.org/v2/directions/foot-walking");
String payload = "{\"coordinates\":[[" + start.getCoordinates() + "],[" + end.getCoordinates() + "]],\"language\":\"fr\"}";
System.out.println(payload); //{"coordinates":[[1.463478,43.562038],[1.471717,43.560787]],"language":"fr"}
byte[] postData = payload.getBytes(StandardCharsets.UTF_8);
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Authorization", API_KEY);
connection.setRequestProperty("Accept", "application/json, application/geo+json, application/gpx+xml, img/png; charset=utf-8");
connection.setDoOutput(true);
try (DataOutputStream wr = new DataOutputStream(connection.getOutputStream())) {
wr.write(postData);
}
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); // Error is right here
String inputLine;
StringBuffer content = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
content.append(inputLine);
}
in.close();
connection.disconnect();
jsonObject = new JSONObject(content.toString());
} catch (IOException | JSONException e) {
e.printStackTrace();
}
return new UPSRoute(jsonObject);
} else {
return getRoute(start, end);
}
}
Here is the error :
java.io.IOException: Server returned HTTP response code: 500 for URL: https://api.openrouteservice.org/v2/directions/foot-walking/json
at java.base/sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1913)
at java.base/sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1509)
at java.base/sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:245)
at UPSRouteService.getRoute(UPSRouteService.java:63)
at Main.main(Main.java:5)
Thanks to Andreas, it was just missing the line :
connection.setRequestProperty("Content-Type", "application/json");
It works fine now.
I'm trying to use HttpURLConnection for connecting to server from Android app which I'm developing. For now, I'm testing the connection code not in an app but as a plain java program with main class. I guess this doesn't make any difference as far as HttpUrlConnection.
Please examine the code snippet. Another issue is even errorStream is throwing null. This I feel is because of malformed URL.
private static String urlConnectionTry() {
URL url; HttpURLConnection connection = null;
try {
String urlParameters = "email=" + URLEncoder.encode("email", "UTF-8") +
"&pwd=" + URLEncoder.encode("password", "UTF-8");
//Create connection
url = new URL("http://example.com/login");
connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
connection.setRequestProperty("uuid", getUuid());
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setInstanceFollowRedirects(true);
//Send request
DataOutputStream wr = new DataOutputStream (
connection.getOutputStream ());
wr.writeBytes (urlParameters);
wr.flush ();
wr.close ();
//Get Response
InputStream is = connection.getErrorStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line;
StringBuffer response = new StringBuffer();
while((line = rd.readLine()) != null) {
response.append(line);
response.append('\r');
}
rd.close();
return response.toString();
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
if(connection != null) {
connection.disconnect();
}
}
}
private static String getUuid() {
try {
Document doc=Jsoup.connect("http://example.com/getUuid").get();
Elements metaElems = doc.select("meta");
for (Element metaElem : metaElems) {
if(metaElem.attr("name").equals("uuid")) {
return metaElem.attr("content");
}
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
You're probably receiving 401 because the credentials that was sent to the server is not authorized- it's probably not registered or the password is incorrect.
As for the null error stream, take a look at this SO answer.
If the connection was not connected, or if the server did not have an error while connecting or if the server had an error but no error data was sent, this method will return null.
It is probably better if you check first the response code using HttpUrlConnection#getResponseCode(). Decide on whether you'll be checking the contents of the error stream based on the response code you get.
Hi I have an Android app that needs to connect to an API (currently running locally) to authenticate the user, so I'm trying to send a POST request with a JSON object as the request body but whenever I try to login I get the following error:
Unexpected status line: ��
java.net.ProtocolException: Unexpected status line: ��
Here's my code:
String API_URL = "http://10.0.2.2:8443/api/";
try {
URL url = new URL(API_URL);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
try {
urlConnection.setDoOutput(true);
urlConnection.setRequestMethod("POST");
urlConnection.setRequestProperty("Content-Type", "application/json");
urlConnection.connect();
JSONObject jsonObject = new JSONObject();
jsonObject.put("customerId", 1);
jsonObject.put("password" , mPassword);
jsonObject.put("username" , mEmail);
DataOutputStream wr = new DataOutputStream(urlConnection.getOutputStream());
wr.writeBytes(jsonObject.toString());
Log.d("REQUEST BODY", jsonObject.toString());
wr.flush();
wr.close();
int response = urlConnection.getResponseCode();
Log.d("RESPONSE", String.valueOf(response));
if(response == HttpURLConnection.HTTP_OK) {
InputStream bis = new BufferedInputStream(urlConnection.getInputStream());
return getStringFromInputStream(bis);
}
}
finally{
urlConnection.disconnect();
}
}
catch(Exception e) {
Log.e("ERROR", e.getMessage(), e);
return null;
}
Can anyone please tell me what I might be doing wrong? Thanks!
EDIT
Not sure if this helps but the problem seems to occur when I call urlConnection.getResponseCode();.
Possibly you are recycling the connection
try adding urlConnection.setRequestProperty("Connection", "close"); before connecting
In my Android app I'm making a post request to an URL. I tried to make the request with chrome extension "Advanced Rest Client" and I get the correct response with the correct status, but in my Android app I don't. I get http status 401 and this error "java.io.FileNotFoundException: http://95.85.53.176/nhi/api/app/session/get"
Here is my Java code -> this code works fine with all other post request i have tried, but not for this url.
public void req()
{
try {
String query = "access_token=xRO8OAiGGpPNjNP0jbPrb99g12vnRNsTcEwha9C2";
URL url = new URL("http://95.85.53.176/nhi/api/app/session/get");
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
//Set to POST
connection.setRequestMethod("POST");
Writer writer = new OutputStreamWriter(connection.getOutputStream());
writer.write(query);
writer.flush();
writer.close();
int status = connection.getResponseCode();
Log.i(LOGTAG, "" + status);
InputStream body = connection.getInputStream();
BufferedReader in = new BufferedReader(new InputStreamReader(body));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
String s = response.toString();
Log.d(LOGTAG, s);
} catch (Exception e) {
// TODO Auto-generated catch block
Log.e(LOGTAG, e.toString());
}
}
Thank you