getInputStream throws EOFException when sending JSON request - java

I get an EOFException from getInputStream in the following Android Code.
private void downloadUrl() {
HttpsURLConnection conn = null;
DataOutputStream printout = null;
try {
try {
conn = (HttpsURLConnection) new URL("some url").openConnection();
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setAllowUserInteraction(false);
conn.setRequestProperty("Accept", "application/json");
conn.setRequestProperty("Content-Type", "application/json; charset=utf-8");
}
catch (ProtocolException e){
}
JSONObject jsonReq = new JSONObject();
jsonReq.put("userID", "id");
jsonReq.put("password", "1234");
OutputStream output = conn.getOutputStream();
try {
OutputStreamWriter wr = new OutputStreamWriter(output);
wr.write(URLEncoder.encode(jsonReq.toString(),"utf-8"));
wr.flush();
wr.close();
}
catch (IOException e) {
}
InputStream in = conn.getInputStream(); //I get EOFException here
try {
BufferedReader rd = new BufferedReader(new InputStreamReader(in));
String responseSingle = null;
while ((responseSingle = rd.readLine()) != null) {
response = response + responseSingle;
}
rd.close();
}
catch (IOException e) {
}
finally {
if (in != null)
in.close();
}
}
catch (IOException e){
}
catch (JSONException e) {
}
finally{
if(conn!=null)
conn.disconnect();
}
}
What is causing this Exception?

public class EOFException extends IOException:
Signals that an end of file or end of stream has been reached unexpectedly during input.
http://docs.oracle.com/javase/7/docs/api/java/io/EOFException.html
You are calling conn.getOutputStream(); and then calling conn.getInputStream(); without resetting. You are already at the end of the file.

Related

Getting Empty response From PHP web API in android

I'm using Asynctask For network call in android Studio.I have php web API's I dont know why but Some of them Not Working in android .
Following is My AsyncTask Class...
private class AsyncAddfriend extends AsyncTask<String, String, String> {
HttpURLConnection conn;
URL url = null;
#Override
protected String doInBackground(String... params) {
try {
url = new URL("http://ishook.com/users/friends/send_friend_request_json/");
} catch (MalformedURLException e) {
e.printStackTrace();
}
try {
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(READ_TIMEOUT);
conn.setConnectTimeout(CONNECTION_TIMEOUT);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
Uri.Builder builder = new Uri.Builder()
.appendQueryParameter("sessionId", params[0])
.appendQueryParameter("UserId", params[1])
.appendQueryParameter("friendId", params[2]);
String query = builder.build().getEncodedQuery();
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(query);
writer.flush();
writer.close();
os.close();
conn.connect();
} catch (IOException e) {
e.printStackTrace();
}
try {
int response_code = conn.getResponseCode();
// Check if successful connection made
if (response_code == HttpURLConnection.HTTP_OK) {
// Read data sent from server
InputStream input = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
StringBuilder result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
// Pass data to onPostExecute method
return (result.toString());
} else {
return ("unsuccessful");
}
} catch (IOException e) {
e.printStackTrace();
return "exception";
} finally {
conn.disconnect();
}
}
}
I'm using same Code for other API's also they all are working fine but this api is not working.
I have Tested This API in post man its working but in not working android .
Hope You will understand My problem....

how can i obtain the response off server and if this contains "open" i can call other method, "contains" always marks error

/Method that sends the GPS pulse every time, when receiving the answer of the server if it contains "open" I have to stop sending pulse The method of eliminating the pulse I already have, I just have to know if the server response contains "open" because the response from the Server is too large string coming from a JSON/
#Override
protected String doInBackground(String... params) {
HttpURLConnection urlConnection = null;
BufferedReader bufferedReader = null;
final String routeId = ControlClass.pref.getString("routeId", "inaccesible");
int routeId2= Integer.parseInt(routeId);
try {
URL url = new URL(params[0]);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("POST");
urlConnection.setUseCaches(false);
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
urlConnection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
DataOutputStream wr = new DataOutputStream(urlConnection.getOutputStream());
JSONObject jsonParam = new JSONObject();
jsonParam.put("route_id", routeId2);
jsonParam.put("timestamp", timestamp);
jsonParam.put("lat", 19.5216103);
jsonParam.put("lon", -99.21071050509521);
Log.d("BANDERA", "LIVE TRACKING");
Log.d("JSON DEL LIVE TRACKING", jsonParam.toString());
System.out.println("Latitud y longitud" + currentLatitude + currentLongitude);
wr.writeBytes(jsonParam.toString());
wr.flush();
wr.close();
urlConnection.connect();
try {
InputStream is = urlConnection.getInputStream();
bufferedReader = new BufferedReader(new InputStreamReader(is));
String line;
StringBuilder response = new StringBuilder();
while ((line = bufferedReader.readLine()) != null) {
response.append(line);
response.append('\r');
}
bufferedReader.close();
if(serverAnswer.contains("open"))
killGps();
serverAnswer = response.toString();
System.out.println("LIVE TRACKING RESPONSE" + serverAnswer);
Log.d("LIVE TRACKING RESPONSE", serverAnswer);
return response.toString();
} catch (FileNotFoundException e) {
Log.d("ERROR: ", "File not found en servidor Response: " + serverAnswer);
}
} catch(Exception e){
e.printStackTrace();
return null;
} finally{
if (urlConnection != null) {
urlConnection.disconnect();
}
try {
if (bufferedReader != null) {
bufferedReader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return serverAnswer;
}
}
If you don't need the entire response, don't store it. Just search each line as you stream it, and exit once you find the text you're looking for:
while ((line = bufferedReader.readLine()) != null) {
if (line.contains("open")) {
killGps();
break;
}
}

HTTP POST request with JSON String in JAVA is not working

I have the below small code to get the json reply from service providers, what i have tried is that to post a http post request but it always throws
java.net.UnknownHostException: directory.qantasloyalty.com
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:177)
at java.net.Socket.connect(Socket.java:519)
at java.net.Socket.connect(Socket.java:469)
at sun.net.NetworkClient.doConnect(NetworkClient.java:157)
at sun.net.www.http.HttpClient.openServer(HttpClient.java:382)
at sun.net.www.http.HttpClient.openServer(HttpClient.java:509)
at sun.net.www.protocol.https.HttpsClient.<init>(HttpsClient.java:278)
at sun.net.www.protocol.https.HttpsClient.New(HttpsClient.java:335)
at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.getNewHttpClient(AbstractDelegateHttpsURLConnection.java:176)
at sun.net.www.protocol.http.HttpURLConnection.plainConnect(HttpURLConnection.java:769)
at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(AbstractDelegateHttpsURLConnection.java:162)
at sun.net.www.protocol.http.HttpURLConnection.getOutputStream(HttpURLConnection.java:861)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getOutputStream(HttpsURLConnectionImpl.java:230)
at Test.Httptestpost.sendPost(Httptestpost.java:124)
at Test.Httptestpost.main(Httptestpost.java:32)
PLease find my code below,
private void sendPost() {
System.getProperties().put("http.proxySet", "true");
System.getProperties().put("http.proxyHost", "proxyurl");
System.getProperties().put("http.proxyPort", "8080");
System.getProperties().put("http.proxyUser", "username");
System.getProperties().put("http.proxyPassword", "pwd");
System.getProperties().put("http.nonProxyHosts", "localhost|127.0.0.1");
String url = "httpsurlhere";
URL obj = null;
try {
obj = new URL(url);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
HttpsURLConnection con = null;
try {
con = (HttpsURLConnection) obj.openConnection();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//add reuqest header
try {
con.setRequestMethod("POST");
} catch (ProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//con.setRequestProperty("User-Agent", USER_AGENT);
//con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
con.setRequestProperty("Content-Type", "application/json;UTF-8");
String urlParameters = "username=demouser&password=aDemoPassword";
String input = "{\"username\":\"demouser\",\"password\":\"aDemoPassword\"}";
System.out.println("input"+input);
System.out.println("url"+con.getURL());
System.out.println("req prop :"+con.getRequestProperties());
// Send post request
con.setDoOutput(true);
DataOutputStream wr;
try {
wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(input);
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Post parameters : " + urlParameters);
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
//print result
System.out.println(response.toString());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Can someone please help me to route the cause
For security purpose I have not shared the exact proxy URL and http post webservice URl also here
please go through these sample codes:-
public static String handlePostRequest(String X, String Y)
throws IOException {
URL url = new URL(X);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("Content-Length",
String.valueOf(Y.length()));
// Write data
OutputStream os = connection.getOutputStream();
os.write(Y.getBytes());
// Read response
String responseSB = "";
BufferedReader br = new BufferedReader(new InputStreamReader(
connection.getInputStream()));
String line;
while ((line = br.readLine()) != null)
responseSB += line;
// Close streams
br.close();
os.close();
return responseSB;
}

HttpUrlConnection is freezing my AsyncTask

In the "doInBackground" function of a AsyncTask, I got the following piece of code :
try
{
URL url = new URL(myUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
Authenticator.setDefault(new Authenticator(){
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication ("myUsername", "myPassword".toCharArray());
}
});
conn.connect();
int response = conn.getResponseCode();
inputStream = conn.getInputStream();
String content = convertInputStreamToString(inputStream);
return content;
catch (Exception e) {
e.printStackTrace();
return null;
}
When the credentials are ok, everything works fine and the ResponseCode is 200. But if I put the wrong credentials, getResponseCode() makes the AsyncTask wait for an answer indefinitely (timeout won't work). Looking at HttpUrlConnection object tells me that the ResponseCode is -1.
I need to handle every situation, even if the user provides a bad credential. How can I get an usable answer? Should I use another class than HttpUrlConnection?
Are you returning String back from this function and are you handling exceptions? Did you write onPostExecute?
Here is the code that works perfectly for me:
URL url = new URL(strUrl);
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Host", "myhost.com");
conn.setRequestProperty("Authorization", "Basic " + Base64.encodeToString(toencode, Base64.DEFAULT));
conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Macintosh; U; PPC; en-US; rv:1.3.1)");
conn.setRequestProperty("Accept-Charset", "UTF-8");
conn.setConnectTimeout (5000) ;
conn.setDoOutput(true);
conn.setDoInput(true);
BufferedInputStream in = new BufferedInputStream(conn.getInputStream());
result = Utilities.readStream(in);
status_code = conn.getResponseCode();
return result;
} catch (MalformedURLException e) {
return e.getMessage();
} catch (ProtocolException e) {
try {
status_code = conn.getResponseCode();
} catch (IOException e1) {
status_code = -1;
}
return e.getMessage();
} catch (IOException e) {
try {
status_code = conn.getResponseCode();
} catch (IOException e1) {
status_code = -1;
}
return e.getMessage();
} catch ( Exception e ) {
try {
status_code = conn.getResponseCode();
} catch (IOException e1) {
status_code = -1;
}
return e.getMessage();
}
finally
{
conn = null;
}

Android POST Request 400 Response code throws Exception

When i send a POST Request to a Server, if the response is 200 i get the JSON body. However for unsuccessful requests the servers send a 400 response code but my android code throws a FileNotFoundException. Is there any difference between reading a 400 response and a 200 response ?
StringBuffer responseBuilder = new StringBuffer();
String line = null;
HttpURLConnection conn = null;
OutputStream out = null;
BufferedReader rd = null;
System.setProperty("http.keepAlive", "false");
try
{
conn = (HttpURLConnection) new URL(requestURL).openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
conn.setAllowUserInteraction(false);
conn.setConnectTimeout(NetworkConstants.CONNECTION_TIMEOUT);
conn.setReadTimeout(NetworkConstants.SOCKET_TIMEOUT);
out = conn.getOutputStream();
Writer writer = new OutputStreamWriter(out, "UTF-8");
String s = formatParams();
Log.d("-------------------------------------------------->", s);
writer.write(s);
writer.flush();
writer.close();
}
catch (Exception e)
{
}
finally
{
if (out != null)
{
try
{
out.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
try
{
rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
while ((line = rd.readLine()) != null)
{
responseBuilder.append(line);
if (!rd.ready())
{
break;
}
}
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
if (conn != null)
{
conn.disconnect();
}
}
String response = responseBuilder.toString();
Log.d("###########################", response);
return response;
Kind Regards,
Use getErrorStream() for this. From the docs:
If the HTTP response indicates that an error occurred, getInputStream() will throw an IOException. Use getErrorStream() to read the error response. The headers can be read in the normal way using getHeaderFields().
Sample code:
httpURLConnection.connect();
int responseCode = httpURLConnection.getResponseCode();
if (responseCode >= 400 && responseCode <= 499) {
Log.e(TAG, "HTTPx Response: " + responseCode + " - " + httpURLConnection.getResponseMessage());
in = new BufferedInputStream(httpURLConnection.getErrorStream());
}
else {
in = new BufferedInputStream(httpURLConnection.getInputStream());
}
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line = "";
while ((line = reader.readLine()) != null) {
urlResponse.append(line);
}
If the response code isn't 200 or 2xx, use getErrorStream() instead of getInputStream() to parse the json and show the message provided by your backend.
I know it's been a long time since the question was asked but for the benefit of other people who are still having this kind of problem please note that another possible cause of the problem is using "connection.getContent()" to get InputStream. like so:
InputStream is = (InputStream) connection.getContent();
this can create a problematic situation where response code larger than 399 will not be processed at all.
so the recommendation is to work directly with getInputStream() and getErrorStream() as shown in previous comments and as in the following example:
HttpURLConnection connection = null;
BufferedReader bufferedReader = null;
try {
String urlString = "http://www.someurl.com";
URL url = new URL(urlString);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream is;
int responseCode = connection.getResponseCode();
if (responseCode < HttpURLConnection.HTTP_BAD_REQUEST) {
is = connection.getInputStream();
} else {
is = connection.getErrorStream();
}
StringBuilder response = new StringBuilder();
bufferedReader = new BufferedReader(new InputStreamReader(is));
String tempLine;
while ((tempLine = bufferedReader.readLine()) != null) {
response.append(tempLine);
}
String serverResponse = response.toString();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (bufferedReader != null) {
try {
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (connection != null) {
connection.disconnect();
}
}

Categories

Resources