Android Parsing HTTP POST response - android

How to extract a specific http header value(for example: Set-Cookie:auth=xyzabc) from the http 200 OK response that is received from the below code -
public void sendPost() {
HttpClient httpClient = new DefaultHttpClient();
HttpPost post = new HttpPost("http://172.26.207.10/myexample/webauth/auth_default_submit");
// Set User-Agent and any other headers you want
// Note: you don't have to set most of the headers manually, for example Content-Type and Content-Length
post.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 5.1; rv:24.0) Gecko/20100101 Firefox/24.0");
post.setHeader("Referer", "http://xxx.xxx.xxx.xx/myexample/webauth/auth_default?app_name=SampleWebAppTesting");
// Add the parameters
List<NameValuePair> parameters = new ArrayList<NameValuePair>();
parameters.add(new BasicNameValuePair("pincode", "9381"));
parameters.add(new BasicNameValuePair("response", "allow"));
parameters.add(new BasicNameValuePair("token", "dc7553b7d7910e51e331d5c3245133ba90b135da1504299510e91984f4e2cf81"));
post.setEntity(new UrlEncodedFormEntity(parameters));
// Do the actual post
HttpResponse response = httpClient.execute(post);
// Read the response
BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
String line;
StringBuffer responseBuffer = new StringBuffer();
while ((line = rd.readLine()) != null) {
responseBuffer.append(line);
}
rd.close();
// Print the results
System.out.println(responseText.toString());
}

Check these SO links:
Android HttpUrlConnection how to read response into pieces
Get header from HttpResponse in Android
http://www.mkyong.com/java/how-to-get-http-response-header-in-java/
Also have a look:
http://www.java2s.com/Code/Java/Network-Protocol/GettingtheResponseHeadersfromanHTTPConnection.htm
http://examples.javacodegeeks.com/core-java/net/urlconnection/get-response-headers-from-http-request/

Related

cUrl HttpPost parameters not recognized(?) by server

I am trying to fetch an authorization key from a server. In the documentation they state that I can retrieve one by executing the following curl command:
$ curl --data "grant_type=authorization_code&code=603372224265" https://gerard2.zportal.nl/api/v2/oauth/token`
I have followed the instructions from stackoverflow and produced the following:
#Override
protected String doInBackground(String... params) {
mAuthorizationCode = params[0];
mSchoolCode = params[1];
HttpClient httpClient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("https://" + mSchoolCode + ".zportal.nl/api/v2/oauth/token");
try{
List<NameValuePair> nameValuePairs = new ArrayList<>(2);
httppost.setHeader("Content-Type", "application/json");
httppost.setHeader("Accept", "application/json");
nameValuePairs.add(new BasicNameValuePair("grant_type", "authorization_code"));
nameValuePairs.add(new BasicNameValuePair("code", mAuthorizationCode));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs, HTTP.UTF_8));
HttpParams parameters = httppost.getParams();
HttpConnectionParams.setConnectionTimeout(parameters, 45000);
HttpConnectionParams.setSoTimeout(parameters, 45000);
HttpResponse response = httpClient.execute(httppost);
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
String line;
while((line = reader.readLine()) != null){
Log.e(LOG_TAG, line);
}
}catch(ClientProtocolException e){
Log.e(LOG_TAG, "Error", e);
}catch(IOException e){
Log.e(LOG_TAG, "IO Error", e);
}
return null;
}
The response the server sends me is:
E/ScheduleRetriever: {"response":{"status":500,"message":"Intern probleem op het portal.","details":"class org.springframework.web.bind.MissingServletRequestParameterException: Required String parameter 'grant_type' is not present","eventId":767369,"startRow":0,"endRow":0,"totalRows":0,"data":[]}
While I did include the POST_parameter "grant_type". Can someone help me figure out why the server says that it did not receive the parameter grant_type?
Thanks.
*EDIT: The code I used expired apparently. Generated a new one and it totally works. Thanks!
You shouldn't be overriding the Content-Type of the POST request to application/json using the line httppost.setHeader("Content-Type", "application/json");
This is most likely causing the server to misinterpret the data since the Content-type of the request should be application/x-www-form-urlencoded.
Remove the following line and it should work:
httppost.setHeader("Content-Type", "application/json");

500 Internal Server Error by post request android

Will HTTP post request cause 500 internal server ERROR?. hmmm if so below is my code and why am i constantly getting 500 Internal server error? what am i missing in the code?.
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost((GetAllNewsURL));
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(
1);
nameValuePairs.add(new BasicNameValuePair("pageNo", "0"));
nameValuePairs.add(new BasicNameValuePair("newsPerPage",
"0"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
stream = entity.getContent();
BufferedReader reader = new BufferedReader(
new InputStreamReader(stream));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
thanks,
for me sometimes because of problem on server side I have to send params as header try the same thing like
HttpPost httppost = new HttpPost((GetAllNewsURL+"?pageNo=0&newsPerPage=0"));
or only pass one param as header hopefully it works

How to pass header to WebView in Android [duplicate]

This question already has answers here:
Send Post request along with HttpHeaders on Android
(2 answers)
Closed 2 years ago.
I am passing post data as Json using postUrl() to WebView in Android. Now I want to pass a header "Content-Type: application/json" also along with that. How to achieve it?
may this will help u :)
HttpPost httpPost = new HttpPost(url_src);
HttpParams httpParameters = new BasicHttpParams();
httpclient.setParams(httpParameters);
StringEntity se = new StringEntity(str,"UTF-8");
se.setContentType("application/json");
httpPost.setEntity(se);
httpPost.setHeader("userId", ""+userId);//userID
httpPost.setHeader("machineId", machineId);//deviceUserMachineID
response = httpclient.execute(httpPost);
I believe this will help: link
Doesn't look like you can actually send headers with postUrl(), only with loadUrl() method.
it possible to post data with header i have done it in my project
I am posting you my code ...
HttpParams par = new BasicHttpParams();
//par.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
int timeoutConnection = 30000;
HttpConnectionParams.setConnectionTimeout(par, timeoutConnection);
int timeoutSocket = 10000;
HttpConnectionParams.setSoTimeout(par, timeoutSocket);
DefaultHttpClient httpClient = new DefaultHttpClient(par);
// httpClient.setParams(par);
HttpPost httpPost = new HttpPost(url);
httpPost = new HttpPost(url);
if(postMessage==null)
throw new IllegalArgumentException("please send post data as well");
byte[] data =postMessage.toString().getBytes("UTF-8");
String base64 = Base64.encodeToString(data, Base64.DEFAULT);
System.out.println("Base64: "+base64);
// httpPost.setEntity(new UrlEncodedFormEntity(params));
httpPost.setEntity(new StringEntity(base64));
httpPost.setHeader("token", app.getToken());
httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
System.out.println("httpEntity.getContent():"+ is );
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
data = sb.toString();
//remember httpconnection should be in background thread
// if you use asynchtask then upper code should be in doinbackground method
//and in onpostexecution do data load in webview
webview.loadData(data, "text/html","UTF-8");

pass data using http post [duplicate]

This question already has answers here:
Sending POST data in Android
(17 answers)
Closed 9 years ago.
i am making one application which should give response on the click of button like
-- REQUEST HEADERS --
User-Agent: XYZ
Host: root.url
Content-Type: application/json; charset=utf-8
Content-Length: 123
...
-- REQUEST BODY --
{
"Apikey": "abcdefgh-ijkl-mnop-qrst-uvwxyz12345",
"Imei": "0123456789012354"
"Gps": {
"Latitude": 1.23,
"Longitude": 4.56
},
// Request specifics go here
}
how to pass this data using http post method
hi check this answer :
https://stackoverflow.com/a/10410693/1168654
http://localtone.blogspot.in/2009/07/post-json-using-android-and-httpclient.html
create array like below and pass it in HttpPost method.
ArrayList<NameValuePair> nameValuePairs1 = new ArrayList<NameValuePair>();
nameValuePairs1.add(new BasicNameValuePair("user_id", ""));
nameValuePairs1.add(new BasicNameValuePair("product_id", ""));
nameValuePairs1.add(new BasicNameValuePair("product_review",""+text));
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(URL);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs1));
HttpResponse responce = httpclient.execute(httppost);
HttpEntity entity = responce.getEntity();
is = entity.getContent();
BufferedReader bufr = new BufferedReader(new InputStreamReader(is1,"iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
sb.append(bufr.readLine() + "\n");
String line = "0";
while ((line = bufr.readLine()) != null)
{
sb.append(line + "\n");
}
is1.close();
result = sb.toString();
that array pass with url and give you result.
As your web service expect JSONObject in a request, you can create and simple set it inside HTTPPost using setEntity().
For example:
JSONObject objRequest = new JSONObject();
objRequest.put("Apikey","abcdefgh-ijkl-mnop-qrst-uvwxyz12345");
objRequest.put("Imei","0123456789012354");
JSONObject objGps = new JSONObject();
objGps.put("Latitude",1.23);
objGps.put("Longitude",4.56);
objRequest.put(Gps, objGps);
Now, here is a way to call webservice using request data:
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httpPost= new HttpPost(url);
post.addHeader("Content-Type", "application/json; charset=utf-8"); // addHeader()
httpPost.setEntity(new StringEntity(objRequest.toString(),"utf-8")); // request data
HttpResponse response = httpclient.execute(httpPost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
Log.e("log_tag", "Error in http connection "+e.toString());
}

Android BufferedInputStream HTTP POST/GET

I Use BufferedInputStream For HTTP POST/GET
But I Get Some Error the Below
java.io.FileNotFoundException: http://XX.XX.XX.XX/WebWS/data.aspx
Transport endpoint is not connected
Why Get This Error. My Code is Below
URL url = new URL(glob.postUrl);
HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
try {
httpConn.setDoInput(true);
httpConn.setDoOutput(true);
httpConn.setRequestMethod("GET");
httpConn.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
httpConn.setRequestProperty("Content-Language", "TR");
httpConn.setConnectTimeout(12000);
Iterator<String> reqProps = hMap.keySet().iterator();
while (reqProps.hasNext()) {
String key = reqProps.next();
String value = hMap.get(key);
httpConn.addRequestProperty(key, value);
}
InputStream in = new BufferedInputStream(httpConn.getInputStream());
StringBuilder builder = new StringBuilder();
String line;
try {
BufferedReader reader = new BufferedReader(
new InputStreamReader(in, "UTF-8"));
while ((line = reader.readLine()) != null) {
builder.append(line);
}
} finally {
in.close();
}
httpConn.disconnect();
Thanks.
Is there any reason you're not using HttpClient?
You can replace your code with something like:
HttpContext httpContext = new BasicHttpContext();
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
HttpResponse response = httpClient.execute(httpGet, httpContext);
int statusCode = response.getStatusLine().getStatusCode();
HttpEntity entity = response.getEntity();
String page = EntityUtils.toString(entity);
You can setup the HttpClient with ClientConnectionManager and HttpParams for security and various http parameters for the client at initialisation (plenty of examples around if you search on class names).
HttpURLConnectionImpl.getInputStream() is known to throw a FileNotFoundException if the HTTP response status code is 400 or higher, i.e. for any error condition on the server side. You should check what the status code really is in order to obtain suitable debug information.
However, I second Mark Fisher's suggestion about using HttpClient, which AFAIK is the preferred way of working with HTTP on Android.

Categories

Resources