JSON not returning on HTTPPost on Android - java

I am having problems calling a simple JSON web service from an Android app. The .execute() completes successfully with an 200-OK Status however I am unable to read any JSON output or text.
For the record, if I HttpPost a regular webpage, like Google.com, I can read and parse all the markup. Also, I am able to call the complete urlWithParams string from the device's browser and I see JSON output in the browser. This works in device's browser:
http://maps.googleapis.com/maps/api/distancematrix/json?origins=Seattle&destinations=San+Francisco&mode=bicycling&language=fr-FR&sensor=false
When the code runs, the reader is always blank and reader.readLine() never runs. Returns an empty string. If I change the URL to Google.com, it works and returns 17,000 characters. Thanks!
protected String doInBackground(String... uri) {
String responseString = null;
try {
//String urlGoogle = "http://google.com";
//String urlWithParams = "http://maps.googleapis.com/maps/api/distancematrix/json?origins=Seattle&destinations=San+Francisco&mode=bicycling&language=fr-FR&sensor=false";
String urlOnly = "http://maps.googleapis.com/maps/api/distancematrix/json";
HttpClient httpclient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(urlOnly);
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("origins", "Seattle"));
nameValuePairs.add(new BasicNameValuePair("destinations", "Cleveland"));
nameValuePairs.add(new BasicNameValuePair("sensor", "false"));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httpPost);
int status = response.getStatusLine().getStatusCode();
HttpEntity entity = response.getEntity();
InputStream is = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
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();
}
responseString = sb.toString();
}}
catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
catch (ClientProtocolException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
return responseString;
}

Maybe you should test other mime types instead of application/json.

1 - Check in your manifest file having INTENET Permission or not.
2 - Use this code its returning data
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
try {
String inputLine;
while ((inputLine = reader.readLine()) != null) {
responseString += inputLine;
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}

Solved! The blank return when calling the JSON page was due to not having the proxy settings defined. Proxy settings were setup on the device however per this post, HttpClient does NOT inherit them.
Adding the following line resolved my issue. The code is now returning JSON.
HttpHost proxy = new HttpHost("172.21.31.239", 8080);
httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);

Related

How to write httpput to java

I want to write put Curl to java:
curl -X PUT -u username:password http://localhost:80/api/client/include/clientID
Thats what I googled but my problem is that how can I pass the value of client_id and client to put since there is an /include between them. I am a bit confused of how to write a curl. Can any one help me?
public String RestPutClient(String url, int newValue, int newValue2) {
// example url : http://localhost:80/api/
DefaultHttpClient httpClient = new DefaultHttpClient();
StringBuilder result = new StringBuilder();
try {
HttpPut putRequest = new HttpPut(url);
putRequest.addHeader("Content-Type", "application/json");
putRequest.addHeader("Accept", "application/json");
JSONObject keyArg = new JSONObject();
keyArg.put("value1", newValue);
keyArg.put("value2", newValue2);
StringEntity input;
try {
input = new StringEntity(keyArg.toString());
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
return success;
}
putRequest.setEntity(input);
HttpResponse response = httpClient.execute(putRequest);
if (response.getStatusLine().getStatusCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ response.getStatusLine().getStatusCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader(
(response.getEntity().getContent())));
String output;
while ((output = br.readLine()) != null) {
result.append(output);
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return result.toString();
}
I assume the parameters you are passing are supposed to represent client and clientID. You simply need to build the URL your passing to HttpPut from your parameters.
If these are your parameters
url = "http://localhost:80/api/";
newValue = "client";
newValue2 = "clientID";
then your HttpPut initialization would look like this
HttpPut putRequest = new HttpPut(url + newValue + "/include/" + newValue2);
Also see:
How do I concatenate two strings in Java?

httpPost setEntity always empty

I'm trying to make a post to a node.js server but for some reason the body is always empty for me no matter what I try.
I'm testing now towards requestb.in and its always empty there too.
This is the code I use for posting:
public static String post(String url, String json) {
StringBuilder stringBuffer = new StringBuilder();
BufferedReader bufferedReader = null;
try {
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpPost httpPost = new HttpPost("http://requestb.in/14a9s7m1");
StringEntity se = new StringEntity("{'string':'string'}", HTTP.UTF_8);
se.setContentType("application/json; charset=UTF-8");
httpPost.setEntity(se);
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
httpPost.setHeader("hmac", Methods.getMethods().getHmac(json));
HttpResponse httpResponse = httpClient.execute(httpPost, localContext);
InputStream inputStream = httpResponse.getEntity().getContent();
bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String readLine = bufferedReader.readLine();
while (readLine != null) {
stringBuffer.append(readLine);
stringBuffer.append("\n");
readLine = bufferedReader.readLine();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (bufferedReader != null) {
try {
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return stringBuffer.toString();
}
This is the requestb.in http://requestb.in/14a9s7m1?inspect
raw body should contain the json string, right?
Any suggestions?
You can make many mistakes when using HttpUrlConnection. I admit that I don't see any error, but this doesn't mean anything.
Since Google doesn't recommend using HttpClient and AndroidHttpClient (except for FROYO or older), but we should use HttpUrlConnection instead, you're on the right way (from a Android perspective).
When using a very lightweight wrapper for HttpUrlConnection called DavidWebb, the code looks like this (I left out hmac-generation):
public class TestWebbRequestBin {
#Test public void stackOverflow20543115() throws Exception {
Webb webb = Webb.create();
webb.setBaseUri("http://requestb.in");
JSONObject jsonObject = new JSONObject();
jsonObject.put("string", "string");
String json = jsonObject.toString(); // {"string":"string"}
Response<String> response = webb
.post("/1g7afwn1")
.header("Accept", "application/json")
.header("Content-type", "application/json")
.header("hmac", "some-hmac-just-a-test")
.body(json)
.asString();
assertEquals(200, response.getStatusCode());
assertTrue(response.isSuccess());
String body = response.getBody();
assertEquals("ok\n", body);
}
}
When the JSON I post looks like in your example, requestb.in does accept it:
json = "{'string':'string'}";
But this is not valid JSON (here tested in node.js):
> JSON.parse("{'string':'string'}")
SyntaxError: Unexpected token '
at Object.parse (native)
at repl:1:7
at REPLServer.self.eval (repl.js:110:21)
at Interface.<anonymous> (repl.js:239:12)
tl;dr
Take care to send valid JSON
Master HttpUrlConnection or use a simple abstraction library
For nasty bugs you could either debug your node.js code (or console.log(req)) or use a tool like Wireshark.
Try this code to send the string.... In HttpPost you should use key value pairs to send the data.
HttpPost httppost = new HttpPost(SERVER_URL);
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("REQUEST", req));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));
HttpResponse response = httpclient.execute(httppost);
I am not sure is this the problems. Can you give a tried?
You are sending invalid JSON format string. This make server unable to accept your invalid json string so your body is empty. To solve this, change following code.
StringEntity se = new StringEntity("{\"string\":\"string\"}", HTTP.UTF_8);
I couldn't get HttpPost to work, but HttpUrlConnection works instead. It solves my problem, but doesn't solve the mysterious no body thing of httpPost.
Here is my solution:
public static String post(String ur2l, String json) {
StringBuilder stringBuffer = new StringBuilder();
BufferedReader bufferedReader = null;
try {
URL url = new URL(ur2l);
HttpURLConnection conn;
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Accept", "application/json");
conn.setRequestProperty("Content-type", "application/json");
conn.setRequestProperty("hmac", Methods.getMethods().getHmac(json));
conn.setDoOutput(true);
OutputStream os = null;
try {
os = conn.getOutputStream();
os.write(json.getBytes());
} catch (Exception e) {
e.printStackTrace();
}
os.close();
conn.connect();
int respCode = conn.getResponseCode();
if (respCode == 200) {
InputStream inputStream = conn.getInputStream();
bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String readLine = bufferedReader.readLine();
while (readLine != null) {
stringBuffer.append(readLine);
stringBuffer.append("\n");
readLine = bufferedReader.readLine();
}
}
} catch (MalformedURLException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
} finally {
if (bufferedReader != null) {
try {
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return stringBuffer.toString();
}

Java application terminates at getOutputStream()

I'm creating an application for our Android devices. The aim of this section is to post a username and password (currently just assigned as a string) to a web service and to receive a login token. When running the code, at the getOutputStream() line, my code terminates and will no progress any further.
I have assigned the android emulator GSM access and also set the proxy and DNS server within Eclipse. I'm not sure where to go with it now!
This is within my onHandleIntent():
protected void onHandleIntent(Intent i) {
try{
HttpURLConnection http_conn = (HttpURLConnection) new URL("http://www.XXXXX.com").openConnection();
http_conn.setRequestMethod("POST");
http_conn.setDoInput(true);
http_conn.setDoOutput(true);
http_conn.setRequestProperty("Content-type", "application/json; charset=utf-8");
String login = URLEncoder.encode("XXXXX", "UTF-8") + "=" + URLEncoder.encode("XX", "UTF-8");
login += "&" + URLEncoder.encode("XXXXX", "UTF-8") + "=" + URLEncoder.encode("XX", "UTF-8");
OutputStreamWriter wr = new OutputStreamWriter(http_conn.getOutputStream());
//TERMINATES HERE
wr.write(login);
wr.flush();
BufferedReader rd = new BufferedReader(new InputStreamReader(http_conn.getInputStream()));
String line = rd.toString();
wr.close();
rd.close();
http_conn.disconnect();
}
catch (IOException e){
}
}
This is my first go at java and have only been writing it for a few days so bear with me if I've missed something obvious.
Thanks
If you want to POST something using HTTP, why not use HTTP POST? ;-)
Here is an example snippet:
public void postData() {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.yoursite.com/script.php");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("id", "12345"));
nameValuePairs.add(new BasicNameValuePair("stringdata", "AndDev is Cool!"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
}
Source: http://www.androidsnippets.com/executing-a-http-post-request-with-httpclient
This may not be the appropriate answer, but will certainly be helpful to you. I have used this code for sending and receiving the request and reply resp, to a webservice.
This code is working, but will need some Refactoring, as i have used some extra variable, which are not needed.
I have used the NameValuePair here for Post
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();
} /*
* catch (ParserConfigurationException e) { // TODO
* Auto-generated catch block e.printStackTrace(); } catch
* (SAXException e) { // TODO Auto-generated catch block
* 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();
}
String line = rd.toString();
should be
String line = rd.readLine();
that might do the trick. rd.toString() gives you a String representation of your BufferedReader. It does not trigger the HTTP operation. I did not test your code, so there might be other errors as well, this was just the obvious one.

Android Httppost

Hi i am using below code to send data to server
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.myurl.com/app/page.php");
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(5);
nameValuePairs.add(new BasicNameValuePair("name", "dave"));
nameValuePairs.add(new BasicNameValuePair("taxi no", "354"));
nameValuePairs.add(new BasicNameValuePair("pack", "0"));
nameValuePairs.add(new BasicNameValuePair("exchk", "1"));
try {
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
try {
HttpResponse response = httpclient.execute(httppost);
String responseBody = EntityUtils.toString(response.getEntity());
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
I can successfully send data to server,but the server return larger amount of data(100Kb-200KB) in text format.I want to convert that text response into json object.so i am assigning all the response into one string to convert json object.
But That Response string contain only less amount of data.
I checked the server it send 112kb file but that response String contain only less data.say around (50kb-75kb).
So can u please any one guide me to solve the problem
ArrayList is an expandable List item. So I have no idea what the purpose of using "5" as an argument. Second thing is BasicNameValuePair contains names and values as arguments. It is a good practice to use single word for a name attribute. Remove
String responseBody = EntityUtils.toString(response.getEntity());
Add following code sample
try {
HttpResponse httpResponse = httpClient.execute(httpPost);
InputStream inputStream = httpResponse.getEntity().getContent();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
StringBuilder stringBuilder = new StringBuilder();
String bufferedStrChunk = null;
while((bufferedStrChunk = bufferedReader.readLine()) != null){
stringBuilder.append(bufferedStrChunk);
}
return stringBuilder.toString();
} catch (ClientProtocolException cpe) {
System.out.println("First Exception caz of HttpResponese :" + cpe);
cpe.printStackTrace();
} catch (IOException ioe) {
System.out.println("Second Exception caz of HttpResponse :" + ioe);
ioe.printStackTrace();
}
This return the page content in a readable format. Then you can pass it to a JSON file by using JSONObject and JSONArray.

Set cookie from HTTP Request

I have get a correct login using HttpRequest to work. It prints the correct html form of the logn page in my toast (just for testing). Now I want to set a cookie from that request. How is this possible?
If it necessary I can provide some code.
I already know about the CookieManager class, but how can I successfully do it?
Thanks in advance!
My code:
public String getPostRequest(String url, String user, String pass) {
HttpClient postClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse response;
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("login", user));
nameValuePairs.add(new BasicNameValuePair("pass", pass));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, HTTP.UTF_8));
response = postClient.execute(httpPost);
if(response.getStatusLine().getStatusCode() == 200) {
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
String result = convertStreamToString(instream);
instream.close();
return result;
}
}
} catch (Exception e) {}
Toast.makeText(getApplicationContext(),
"Connection failed",
Toast.LENGTH_SHORT).show();
return null;
}
private String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
Well, this is pretty much it. convertStreamToString() function converts the InputStream into a String (plain HTML code), which I "toast" out to just test it (so it work), so the code is working though. Now to set the cookie. :-)
This is what I've reached for now:
// inside my if (entity != null) statement
List<Cookie> cookies = postClient.getCookieStore().getCookies();
String result = cookies.get(1).toString();
return result;
When I have logged in, the CookieList id 1 contains a value, otherwise the value is standard. So for now I know the difference in value, but how can I continue?
I think Android ships with Apache HttpClient 4.0.
You can check Chapter 3. HTTP state management topic from HttpClient Tutorial.
You can also refer similar questions on SO:
Android project using httpclient --> http.client (apache), post/get method
How do I manage cookies with HttpClient in Android and/or Java?
Also Check this example for usage: http://svn.apache.org/repos/asf/httpcomponents/httpclient/branches/4.0.x/httpclient/src/examples/org/apache/http/examples/client/ClientFormLogin.java

Categories