I have this code on my Android phone.
URI uri = new URI(url);
HttpPost post = new HttpPost(uri);
HttpClient client = new DefaultHttpClient();
HttpResponse response = client.execute(post);
I have a asp.net webform application that has in the page load this
Response.Output.Write("It worked");
I want to grab this Response from the HttpReponse and print it out. How do I do this?
I tried response.getEntity().toString() but it just seems to print out the address in memory.
Thanks
Use ResponseHandler. One line of code. See here and here for sample Android projects using it.
public void postData() {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.yoursite.com/user");
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
ResponseHandler<String> responseHandler=new BasicResponseHandler();
String responseBody = httpclient.execute(httppost, responseHandler);
JSONObject response=new JSONObject(responseBody);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
}
add combination of this post and complete HttpClient at - http://www.androidsnippets.org/snippets/36/
I would just do it the old way. It's a more bulletproof than ResponseHandler, in case you get different content types in the response.
ByteArrayOutputStream outstream = new ByteArrayOutputStream();
response.getEntity().writeTo(outstream);
byte [] responseBody = outstream.toByteArray();
I used the following code
BufferedReader r = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuilder total = new StringBuilder();
String line = null;
while ((line = r.readLine()) != null) {
total.append(line);
}
r.close();
return total.toString();
The simplest approach is probably using org.apache.http.util.EntityUtils:
String message = EntityUtils.toString(response.getEntity());
It reads the contents of an entity and returns it as a String. The content is converted using the character set from the entity (if any), failing that, "ISO-8859-1" is used.
If necessary, you can pass a default character set explicitly - e.g.
String message = EntityUtils.toString(response.getEntity(). "UTF-8");
It gets the entity content as a String, using the provided default character set if none is found in the entity. If the passed default character set is null, the default "ISO-8859-1" is used.
This code will return the entire response message in respond as a String, and status code in rsp, as an int.
respond = response.getStatusLine().getReasonPhrase();
rsp = response.getStatusLine().getStatusCode();`
Related
I am trying to do a HTTP post request to a web API and then parse the received HttpResponse and access the key value pairs in the body. My code is like this:
public class access {
// http://localhost:8080/RESTfulExample/json/product/post
public static void main(String[] args) {
HttpClient httpclient = HttpClients.createDefault();
HttpPost httppost = new HttpPost("https://XXXXXXX/RSAM_API/api/Logon");
// Request parameters and other properties.
List<NameValuePair> urlParameters = new ArrayList<NameValuePair>(2);
urlParameters.add(new BasicNameValuePair("UserId", "XXXXX"));
urlParameters.add(new BasicNameValuePair("Password", "XXXXXX"));
try {
httppost.setEntity(new UrlEncodedFormEntity(urlParameters));
//Execute and get the response.
HttpResponse response = httpclient.execute(httppost);
BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
String line;
while(null !=(line=rd.readLine())){
System.out.println(line);
}
System.out.println(response);
String resp = EntityUtils.toString(response.getEntity());
JSONObject obj = new JSONObject(resp);
}
catch (Exception e){
e.printStackTrace();
}
}
}
I am trying to access the body by converting it to a JSONObject with these 2 lines of code:
String resp = EntityUtils.toString(response.getEntity());
JSONObject obj = new JSONObject(resp);
But I get an error in the second line saying:
JSONObject
(java.util.Map)
in JSONObject cannot be applied
to
(java.lang.String)
Not sure if this is the correct approach. Is there a way to do what I am trying to do?
Any help would be appreciated, Thank you.
EDIT:
So when I try to print the response body using the following lines,
String resp = EntityUtils.toString(response.getEntity());
System.out.println(resp);
I get the result: {"APIKey":"xxxxxxxxxxxxxx","StatusCode":0,"StatusMessage":"You have been successfully logged in."}
I am looking for a way to parse this result and then access each element. Is there a way to do this?
According to JsonSimple's JsonObject documentation it takes map in the constructor but not a String. So the error you are getting what it says.
You should use JSONParser to parse the string first.
Its also better to provide the encoding as part of EntityUtils.toString say UTF-8 or 16 based off your scenario.
IOUtils.toString() from Apache Commons IO would be a better choice to use too.
Try the below line to parse the JSON:
JSONParser parser = new JSONParser();
JSONObject obj = (JSONObject) parser.parse(resp);
The above lines will vaildate the JSON and through exception if the JSON is invalid.
You don't need to read the response in the extra while loop. EntityUtils.toString(response.getEntity()); will do this for you. As you read the response stream before, the stream is already closed when comming to response.getEntity().
I have the code below, and my problem is that the response.status is 200 (is ok) and my response body is empty and it should return a json response. Is the problem the length maybe?:`
HttpPost post = new HttpPost("http://localhost:8080/rest/login");
httpClient = HttpClients.createDefault();
List<NameValuePair> formParams = new ArrayList<NameValuePair>();
NameValuePair pair = new BasicNameValuePair("token",token);
formParams.add(pair);
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formParams);
post.setEntity(entity);
HttpResponse response = httpClient.execute(post);
this.code = response.getStatusLine().getStatusCode();
InputStream body = response.getEntity().getContent();
BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));`
I had similar problem. In my case it was also very strange, that when url contained IP instead of hostname, it worked (I get the nonempty response).
However, setting netscape cookie specs helped in my case.
httpClientBuilder.setDefaultRequestConfig(RequestConfig.custom()
.setCookieSpec(CookieSpecs.NETSCAPE)
.build());
I have a function with which I want to POST two variables to the php side, after these two variables match and the server processes the result, I want to return result in JSON. As of now my set header property looks like the following:
httppost.setHeader("Content-type", "application/json");
But while reading on at Wikipedia I found that the content type should be application/x-www-form-urlencoded and to accept JSON it should be Accept: application/json I want more clarity on this, how do I modify my code to achieve my desired result? As of now I am using local host and my POST variables seem to be not delivered on the php side. Following is my complete function:
public void parse(String last, String pwd){
String lastIndex = last;
DefaultHttpClient http = new DefaultHttpClient(new BasicHttpParams());
System.out.println("URL is: "+CONNECT_URL);
HttpPost httppost = new HttpPost(CONNECT_URL);
httppost.setHeader("Content-type", "application/json");
try{
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("key", password));
nameValuePairs.add(new BasicNameValuePair("last_index", lastIndex));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
System.out.println("Post variables(Key): "+password+"");
System.out.println("Post variables(last index): "+lastIndex);
HttpResponse resp = http.execute(httppost);
HttpEntity entity = resp.getEntity();
ins = entity.getContent();
BufferedReader bufread = new BufferedReader(new InputStreamReader(ins, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while((line = bufread.readLine()) != null){
sb.append(line +"\n");
}
result = sb.toString();
System.out.println("Result: "+result);
// readAndParseJSON(result);
}catch (Exception e){
System.out.println("Error: "+e);
}finally{
try{
if(ins != null){
ins.close();
}
}catch(Exception smash){
System.out.println("Squish: "+smash);
}
}
// return result;
}
You have a caps problem. Try "Content-Type" rather than "Content-type" (or use the const HTTP.CONTENT_TYPE).
It appears that your code is actually doing what that article describes, except that
// httppost.setHeader("Content-type", "application/json");
httppost.setHeader("Content-Type", "application/x-www-form-urlencoded");
httppost.setHeader("Accept", "application/json");
You are adding the x-www-form-urlencoded content here
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
I am trying to send a query url
String url = String.format(
"http://xxxxx/xxx/xxx&message=%s",myEditBox.getText.toString());
// Create a new HttpClient and Post Header
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
httpclient.getCookieStore().addCookie(cooki);
try {
ResponseHandler<String> responseHandler = new BasicResponseHandler();
httpclient.getParams().setParameter("http.connection-manager.timeout", 15000);
String response = httpclient.execute(httppost, responseHandler);
gives me error, illegal character at query. That's white space probably. How to deal with this issue?
Best Regards
You need to encode your url.
String query = URLEncoder.encode(myEditBox.getText.toString(), "utf-8");
String url = "http://stackoverflow.com/search?q=" + query;
Can you try
httpclient.setRequestProperty("Accept-Charset","UTF-8");
url="http://xxxxx/xxx/xxx&message="+URLEncoder.encode(myEditBox.getText.toString(), "UTF-8");
Try .trim() while get value from edittext.
May be whitespace come from edittext and also use "utf-8".
see below code.
String value = URLEncoder.encode(myEditBox.getText.toString().trim(), "utf-8");
String url = "http://xxxxx/xxx/xxx&message=%s" + value;
I have this code on my Android phone.
URI uri = new URI(url);
HttpPost post = new HttpPost(uri);
HttpClient client = new DefaultHttpClient();
HttpResponse response = client.execute(post);
I have a asp.net webform application that has in the page load this
Response.Output.Write("It worked");
I want to grab this Response from the HttpReponse and print it out. How do I do this?
I tried response.getEntity().toString() but it just seems to print out the address in memory.
Thanks
Use ResponseHandler. One line of code. See here and here for sample Android projects using it.
public void postData() {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.yoursite.com/user");
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
ResponseHandler<String> responseHandler=new BasicResponseHandler();
String responseBody = httpclient.execute(httppost, responseHandler);
JSONObject response=new JSONObject(responseBody);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
}
add combination of this post and complete HttpClient at - http://www.androidsnippets.org/snippets/36/
I would just do it the old way. It's a more bulletproof than ResponseHandler, in case you get different content types in the response.
ByteArrayOutputStream outstream = new ByteArrayOutputStream();
response.getEntity().writeTo(outstream);
byte [] responseBody = outstream.toByteArray();
I used the following code
BufferedReader r = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuilder total = new StringBuilder();
String line = null;
while ((line = r.readLine()) != null) {
total.append(line);
}
r.close();
return total.toString();
The simplest approach is probably using org.apache.http.util.EntityUtils:
String message = EntityUtils.toString(response.getEntity());
It reads the contents of an entity and returns it as a String. The content is converted using the character set from the entity (if any), failing that, "ISO-8859-1" is used.
If necessary, you can pass a default character set explicitly - e.g.
String message = EntityUtils.toString(response.getEntity(). "UTF-8");
It gets the entity content as a String, using the provided default character set if none is found in the entity. If the passed default character set is null, the default "ISO-8859-1" is used.
This code will return the entire response message in respond as a String, and status code in rsp, as an int.
respond = response.getStatusLine().getReasonPhrase();
rsp = response.getStatusLine().getStatusCode();`