POST using HttpURLConnection timeouts from device but not from emulator - java

I have a server which I'm doing GET requests fine both from emulator and from device(galaxy s2, 4.1.2).
But POST-ing from device throws java.io.FileNotFoundException: http://*.*.*.*:8080/MyProject/rest/orderwhich when I check on the server is a SocketTimeoutException
It timeouts even before my specified timeout(60 seconds)!
My POST code is as follows:
public String postOrder(String orderJSON, String uri) throws Exception {
URL url = new URL(uri);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("Accept", "application/json");
con.setRequestProperty("Content-type", "application/json");
con.setConnectTimeout(2*TIMEOUT_VALUE);//TIMEOUT_VALUE=30000
con.setReadTimeout(2*TIMEOUT_VALUE);
// con.setDoOutput(true);
con.setChunkedStreamingMode(0);
OutputStream out = null;
try {
out = new BufferedOutputStream(con.getOutputStream());
out.write(orderJSON.getBytes("utf-8"));
} catch (IOException e) {
e.printStackTrace();
throw new Exception(e);
} finally {
if (out != null) {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
String json = readStream(con.getInputStream());
con.disconnect();
return json;
}
private String readStream(InputStream in) throws Exception {
BufferedReader reader = null;
StringBuilder response = new StringBuilder();
try {
reader = new BufferedReader(new InputStreamReader(in, "utf-8"));
String line = "";
while ((line = reader.readLine()) != null) {
response.append(line);
}
} catch (IOException e) {
e.printStackTrace();
throw new Exception(e);
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return response.toString();
}
What could be wrong?
Thanks
EDIT:
Same is happening with Apache HTTP client:
Emulator Android Version: 4.1.2
Device Android Version: 4.1.2
public void postOrder(String orderJSON, String uri) throws Exception{
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, 120000);
HttpConnectionParams.setSoTimeout(httpParameters, 120000);
HttpConnectionParams.setTcpNoDelay(httpParameters, true);
DefaultHttpClient client = new DefaultHttpClient(httpParameters);
HttpPost httpPost = new HttpPost(uri);
StringEntity entity = new StringEntity(orderJSON);
httpPost.setEntity(entity);
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
HttpResponse httpResponse = client.execute(httpPost);
int code = httpResponse.getStatusLine().getStatusCode();
String codeString = String.valueOf(code);
if(!codeString.startsWith("2")){
throw new Exception("Server ERROR, httpCode; " + code
+ ", response entity: "
+ EntityUtils.toString(httpResponse.getEntity()));
}
}

Related

My program won't pass through HttpPost

In my CountryActivity.java I have a HttpRequest to retrieve json information of the wikipedia.
This is the code I use AsyncTask:
private class DownloadFilesTask extends AsyncTask<URL, Integer, String> {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("https://en.wikipedia.org/w/api.php?format=json&action=query&prop=extracts&exintro=&explaintext=&titles=Portugal");
protected String doInBackground(URL... urls) {
HttpResponse httpResponse = null;
try {
httpResponse = httpClient.execute(httpPost);
} catch (IOException e) {
e.printStackTrace();
}
HttpEntity httpEntity = httpResponse.getEntity();
try {
is = httpEntity.getContent();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
System.out.println(line);
}
is.close();
return sb.toString();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String result) {
showDialog(Integer.parseInt("Downloaded "));
}
}
And, to call the class in my activity I use new DownloadFilesTask();.
The problem is, when I debug my private class, the debugger stops in the line HttpPost httpPost = new HttpPost("https://en.wikipedia.org/w/api.php?format=json&action=query&prop=extracts&exintro=&explaintext=&titles=Portugal"); and it can't even retrieve the json. Do you know what may be happening? My app doesn't crash or nothing...
This is my logcat: https://pastebin.com/EgVrjfVx
Open connection to url with HttpURLConnection and set setRequestMethod() to GET
URL obj = new URL("https://en.wikipedia.org/w/api.php?format=json&action=query&prop=extracts&exintro=&explaintext=&titles=Portugal");
HttpURLConnection http = (HttpURLConnection) obj.openConnection();
http.setRequestMethod("GET");
then gets its input stream and read via BufferedReader to your build.
BufferedReader reader = new BufferedReader(new InputStreamReader(http.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
reader.close();
String json_string = sb.toString(); // your json data
Check here full example to understand batter.

HttpURLConnection response is not working

In my project I have url
like:
localhost:8080/myproject/examples/12
It contains Json values..To access this field Need to put access key as Header.
Now, What I have done is that :
private String doHttpUrlConnectionAction(String desiredUrl)
throws Exception
{
URL url = null;
BufferedReader reader = null;
StringBuilder stringBuilder;
try
{
// create the HttpURLConnection
url = new URL(desiredUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// just want to do an HTTP GET here
connection.setRequestMethod("GET");
// connection.setRequestProperty("Content-Type","application/json");
connection.setRequestProperty("API-KEY", "value");
// uncomment this if you want to write output to this url
connection.setDoOutput(true);
// give it 15 seconds to respond
connection.setReadTimeout(15*1000);
connection.connect();
// read the output from the server
// reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
StringBuilder sb = new StringBuilder();
BufferedReader rd = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
sb.append(line);
}
return sb.toString();
}
catch (Exception e)
{
e.printStackTrace();
throw e;
}
finally
{
// close the reader; this can throw an exception too, so
// wrap it in another try/catch block.
if (reader != null)
{
try
{
reader.close();
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
}
}
}
this code returns output :
Response Code : 200
<table border="0" cellpadding="4" cellspacing="0"><thead><tr><th>status</th><th>statusCode</th><th>data</th></tr></thead><tbody><tr><td statusCode="200" status="1">Array</td></tr></tbody></table>
But when I am accessing this code in httclient, I am getting value properly..
public String ReadHttpResponse(String url){
StringBuilder sb= new StringBuilder();
HttpClient client= new DefaultHttpClient();
HttpGet httpget = new HttpGet(url);
httpget.addHeader("API-KEY", "value");
try {
HttpResponse response = client.execute(httpget);
StatusLine sl = response.getStatusLine();
int sc = sl.getStatusCode();
if (sc==200)
{
HttpEntity ent = response.getEntity();
InputStream inpst = ent.getContent();
BufferedReader rd= new BufferedReader(new InputStreamReader(inpst));
String line;
while ((line=rd.readLine())!=null)
{
sb.append(line);
}
// System.out.println(sb.toString());
}
else
{
System.out.println("I didn't get the response!");
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return sb.toString();
}
Here,I am getting output properly..
Where is the problem in HttpUrlConnection?? What am I doing wrong here?? I have to use HttpUrlConnection.Please guys help me out..
You can make code logic like this for both request POST and GET. It helps to reduce code complexity. You can make one method for that and pass parameter to it as needed for GET and POST methods.
HttpURLConnection urlConnection = null;
try {
// http client
murl=new URL(url);
urlConnection = (HttpURLConnection) murl.openConnection();
urlConnection.setRequestProperty("Content-Type", "application/json;odata=verbose");
urlConnection.setRequestProperty("Accept", "application/json;odata=verbose");
// Checking http request method type
if (method == POST) {
urlConnection.setRequestMethod("POST");
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
if(!jsondata.equals("null")) {
OutputStream os = urlConnection.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(jsondata);
writer.flush();
writer.close();
os.close();
}
} else if (method == GET) {
// appending params to url
urlConnection.setRequestMethod("GET");
}
resCode = urlConnection.getResponseCode();
Log.i("TAG", "response code=>" + resCode);

HttpURLConnection GET request on Android gives weird 501 code

I have a weird issue when using HttpURLConnection on android it gives me a status code 501 but when I try the request on curl, it gives me status code 200.
curl -X GET \
-H "Accept-Charset: UTF-8" \
https://domain.com/v1/resource?token=token12345
This is my HttpURLConnection GET request snippet
public MyResponse get(String params) {
HttpURLConnection connection = null;
InputStreamReader inputStream = null;
BufferedReader reader = null;
MyResponse response = null;
String tokenParam = "?token=" + params;
try {
URL url = new URL(BASE_URL + API_VER + mResource + tokenParam);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod(Method.GET);
connection.setRequestProperty(Header.ACCEPT_CHARSET, Value.UTF_8);
connection.setDoInput(true);
connection.setDoOutput(true);
connection.connect();
int statusCode = connection.getResponseCode(); // code 501
inputStream = new InputStreamReader(connection.getInputStream());
reader = new BufferedReader(inputStream);
StringBuilder message = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
message.append(line);
}
response = new MyResponse();
response.setMessageBody(message.toString());
response.setStatusCode(statusCode);
if (statusCode == HTTP_OK || statusCode == HTTP_CREATED) {
response.setSuccess(true);
} else {
response.setSuccess(false);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (connection != null) connection.disconnect();
try {
if (inputStream != null) inputStream.close();
if (reader != null) reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return response;
}
Am I missing anything?
setDoOutput(true) is used for POST and PUT requests for sending (output) a request body. Usually we don't need this for GET requests. Found it here
Ignore the timeout stuff if you don't need it.
The method at the bottom just takes an input stream and converts it into a response for you.
Hope it helps.
public boolean genLogon(){
HttpGet m_httpGet = null;
HttpResponse m_httpResponse = null;
// setup timeout params for the socket and the time to connect
HttpParams httpParameters = new BasicHttpParams();
int timeoutConnection = CONNECTION_TIMEOUT;
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
int timeoutSocket = DATA_TIMEOUT;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
// Create a http client with the parameters
HttpClient m_httpClient = new DefaultHttpClient(httpParameters);
String result = null;
try {
// Create a get object
m_httpGet = new HttpGet("https://domain.com/v1/resource?token=token12345");
m_httpGet.setHeader(Accept-Charset, "UTF-8");
m_httpResponse = m_httpClient.execute(m_httpGet);
HttpEntity entity = m_httpResponse.getEntity();
if (entity != null) {
// Get the input stream and read it out into response
InputStream instream = entity.getContent();
result = convertStreamToString(instream);
// now you have the string representation of the HTML request
instream.close();
}
} catch (ConnectTimeoutException cte) {
// Toast.makeText(MainApplication.m_context, "Connection Timeout", Toast.LENGTH_SHORT).show();
return false;
} catch (Exception e) {
return false;
} finally {
m_httpClient.getConnectionManager().closeExpiredConnections();
}
// See if we have a response
if (m_httpResponse == null) {
return false;
}
// check status
if (m_httpResponse.getStatusLine() == null) {
return false;
}
// If the status code is okay (200)
if (m_httpResponse.getStatusLine().getStatusCode() == 200) {
//Handle the repsonse
return true
} else {
// response code not 200
}
return false;
}
private static String convertStreamToString(InputStream is) {
/*
* To convert the InputStream to String we use the BufferedReader.readLine() method. We iterate until the
* BufferedReader return null which means there's no more data to read. Each line will appended to a
* StringBuilder and returned as String.
*/
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}

pass parameters via http post method

I have two text boxes, 1 for username and the other for password.
I wanted to pass what the user enters into the edit texts with the post method
String request = "https://beta135.hamarisuraksha.com/web/webservice/HamariSurakshaMobile.asmx/getIMSafeAccountInfoOnLogon";
URL url;
try {
url = new URL(request);
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setInstanceFollowRedirects(false);
connection.setRequestMethod("POST");
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded;");// boundary="+CommonFunctions.boundary
connection.setUseCaches(false);
DataOutputStream wr = new DataOutputStream(
connection.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
int responseCode = connection.getResponseCode();
/*
* System.out.println("\nSending 'POST' request to URL : " +
* url); System.out.println("Post parameters : " +
* urlParameters);
*/
System.out.println("Response Code : " + responseCode);
InputStream errorstream = connection.getErrorStream();
BufferedReader br = null;
if (errorstream == null) {
InputStream inputstream = connection.getInputStream();
br = new BufferedReader(new InputStreamReader(inputstream));
} else {
br = new BufferedReader(new InputStreamReader(errorstream));
}
String response = "";
String nachricht;
while ((nachricht = br.readLine()) != null) {
response += nachricht;
}
// print result
// System.out.println(response.toString());
return response.toString();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
} catch (ProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
if i am getting your question correctly , you need to pass your parameters to a web service. in my case i have implemented a method to get the web service response by giving the url and the values as parameters. i think this will help you.
public JSONObject getJSONFromUrl(JSONObject parm,String url) throws JSONException {
InputStream is = null;
JSONObject jObj = null;
String json = "";
// Making HTTP request
try {
// defaultHttpClient
/*JSONObject parm = new JSONObject();
parm.put("agencyId", 27);
parm.put("caregiverPersonId", 47);*/
/* if(!(jObj.isNull("d"))){
jObj=null;
}
*/
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.addHeader("Content-Type", "application/json; charset=utf-8");
HttpEntity body = new StringEntity(parm.toString(), "utf8");
httpPost.setEntity(body);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
/* String response = EntityUtils.toString(httpEntity);
Log.w("myApp", response);*/
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// JSONObject jObj2 = new JSONObject(json);
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
this method take two parameters. one is the url, other one is the values that we should send to the web service. and simply returns the json object. hope this will help you
EDIT
to pass your username and password just use below code
JsonParser jp = new JsonParser(); // create instance for the jsonparse class
String caregiverID = MainActivity.confirm.toString();
JSONObject param = new JSONObject();
JSONObject job = new JSONObject();
try {
param.put("username", yourUserNAme);
job = jp.getJSONFromUrl(param, yourURL);

How do I display a Java HttpPost object as a string?

I am creating an HttpPost object in Android to communicate with a server operated by a client. Unfortunately the server isn't providing either of us with very useful error messages; I would like to see the content of the HttpPost object as a string so I can send it to our client and he can compare it with what he's expecting.
How can I convert an HttpPost object into a string that reflects how it would look as it arrived at the server?
Should use it after execute
public static String httpPostToString(HttpPost httppost) {
StringBuilder sb = new StringBuilder();
sb.append("\nRequestLine:");
sb.append(httppost.getRequestLine().toString());
int i = 0;
for(Header header : httppost.getAllHeaders()){
if(i == 0){
sb.append("\nHeader:");
}
i++;
for(HeaderElement element : header.getElements()){
for(NameValuePair nvp :element.getParameters()){
sb.append(nvp.getName());
sb.append("=");
sb.append(nvp.getValue());
sb.append(";");
}
}
}
HttpEntity entity = httppost.getEntity();
String content = "";
if(entity != null){
try {
content = IOUtils.toString(entity.getContent());
} catch (Exception e) {
e.printStackTrace();
}
}
sb.append("\nContent:");
sb.append(content);
return sb.toString();
}
snippet
I usually do post in this way (The server answer is a JSON object) :
try {
postJSON.put("param1", param1);
postJSON.put("param2",param2);
} catch (JSONException e) {
e.printStackTrace();
}
String result = JSONGetHTTP.postData(url);
if (result != null) {
try {
JSONObject jObjec = new JSONObject(result);
}
} catch (JSONException e) {
Log.e(TAG, "Error setting data " + e.toString());
}
}
And postData is:
public static String postData(String url, JSONObject obj) {
// Create a new HttpClient and Post Header
HttpClient httpclient = null;
try {
HttpParams myParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(myParams, 30000);
HttpConnectionParams.setSoTimeout(myParams, 30000);
httpclient = new DefaultHttpClient(myParams);
} catch (Exception e) {
Log.e("POST_DATA", "error in httpConnection");
e.printStackTrace();
}
InputStream is = null;
try {
HttpPost httppost = new HttpPost(url.toString());
//Header here httppost.setHeader();
StringEntity se = new StringEntity(obj.toString());
httppost.setEntity(se);
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
// // Do something with response...
is = entity.getContent();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// convert response to string
BufferedReader reader = null;
String result = null;
try {
reader = new BufferedReader(new InputStreamReader(is, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
result = sb.toString();
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
} finally {
try {
if (reader != null)
reader.close();
if (is != null)
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (result != null) {
try {
#SuppressWarnings("unused")
JSONObject jObjec = new JSONObject(result);
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
}
return result;
}
Hope it helps
Well i actually did HTTP-Post using NameValuePair...... I am showing the code which i use to do an HTTP-Post and then converting the Response into a String
See the below Method code:
public String postData(String url, String xmlQuery) {
final String urlStr = url;
final String xmlStr = xmlQuery;
final StringBuilder sb = new StringBuilder();
Thread t1 = new Thread(new Runnable() {
public void run() {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(urlStr);
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("xml", xmlStr));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
Log.d("Vivek", response.toString());
HttpEntity entity = response.getEntity();
InputStream i = entity.getContent();
Log.d("Vivek", i.toString());
InputStreamReader isr = new InputStreamReader(i);
BufferedReader br = new BufferedReader(isr);
String s = null;
while ((s = br.readLine()) != null) {
Log.d("YumZing", s);
sb.append(s);
}
Log.d("Check Now",sb+"");
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
t1.start();
try {
t1.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Getting from Post Data Method "+sb.toString());
return sb.toString();
}

Categories

Resources