How to pass header to WebView in Android [duplicate] - android

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");

Related

Get the XML entity passed in body - HTTP Put method in Android

I wanted to retrieve the XML entity passed in body of HTTP Put method. I used the below code,
DefaultHttpServerConnection conn = new DefaultHttpServerConnection();
conn.bind(serverSocket.accept(), new BasicHttpParams());
HttpRequest request = conn.receiveRequestHeader();
conn.receiveRequestEntity((HttpEntityEnclosingRequest)request);
HttpEntity entity = ((HttpEntityEnclosingRequest)request).getEntity();
System.out.println(EntityUtils.toString(entity));
I could get the norma strings, but when trying to pass the XML entity, I could not even see the print statement.
I hope this code help you.
HttpPost httppost = new HttpPost(SERVICE_EPR);
StringEntity se = new StringEntity(SOAPRequestXML,HTTP.UTF_8);
se.setContentType("text/xml");
httppost.setHeader("Content-Type","application/soap+xml;charset=UTF-8");
httppost.setEntity(se);
HttpClient httpclient = new DefaultHttpClient();
BasicHttpResponse httpResponse =
(BasicHttpResponse) httpclient.execute(httppost);
response.put("HTTPStatus",httpResponse.getStatusLine().toString());
PFB the solution,
DefaultHttpServerConnection conn = new DefaultHttpServerConnection();
params = new BasicHttpParams();
conn.bind(socket, params);
//Extracting the information from the requested URI
HttpRequest request = conn.receiveRequestHeader();
conn.receiveRequestEntity((HttpEntityEnclosingRequest)request);
HttpEntity httpEntity = ((HttpEntityEnclosingRequest)request).getEntity();
if(httpEntity != null){
InputStream instream = httpEntity.getContent();
try {
// do something useful
String myString = IOUtils.toString(instream, "UTF-8");
Log.e(TAG,">>>> http body > "+myString);
} finally {
instream.close();
}
}
Don't put any log or print statements using the data you received, I was getting 'Content already consumed' exception. I had used several logs using the httpEntity i received and that was causing the problem for me. I commented those(marked yellow) and started working.
PF the Apache doc for reference,
http://hc.apache.org/httpcomponents-core-ga/tutorial/pdf/httpcore-tutorial.pdf

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

JSON String too Large for StringEntity

In my app I turn an image into a bas64 string and add it to a JSON object to send to the server. The problem seems to be that the string is too large? Originally I was getting an out of Memory error now the response just returns null and Ive debugged it to the point where I have found it to be that the String I pass to my StringEntity Object is too large. I have read alot of other answers but none have worked or they just don't quite apply to what I need to do. The Code is as follows
#Override
protected String doInBackground(JSONArray... params) {
JSONObject allPostObj = new JSONObject();
try {
allPostObj.put("receiptImgs", params[0]);
//Log.e("in obj Try" , allPostObj.toString());
DefaultHttpClient httpClient = new DefaultHttpClient();
// WCF service path
HttpPost httpPost = new HttpPost("http://localhost/path");
HttpParams httpParameters = new BasicHttpParams();
// Set the timeout in milliseconds until a connection is established.
// The default value is zero, that means the timeout is not used.
int timeoutConnection = 10000;
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
// Set the default socket timeout (SO_TIMEOUT)
// in milliseconds which is the timeout for waiting for data.
int timeoutSocket = 10000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
httpPost.setParams(httpParameters);
StringEntity se = new StringEntity(allPostObj.toString());
Log.e("DEBUGGING",allPostObj.toString());
se.setContentType("application/json;charset=UTF-8");
httpPost.setEntity(se);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
BufferedReader reader = new BufferedReader(new InputStreamReader(httpEntity.getContent()));
String readLine = reader.readLine();
Log.d("DEBUG RESPONSE",readLine);
JSONObject jsonResponse = new JSONObject(readLine);
answer = jsonResponse.getString("saveImageResult");
Log.e("returning", answer);
}
And replacing the line
StringEntity se = new StringEntity(allPostObj.toString());
With:
StringEntity se = new StringEntity("{\"receiptImgs\":[{\"imgString\":\"\",\"imgPath\":\"test\"}]}");
Works just fine
Any ideas will be greatly appreciated
You should not use StringEntity for large content, you should switch to FileEntity or InputStreamEntity, depending on where you store your data.
quick fix you may try (not compiled/tested):
InputStream stream = new ByteArrayInputStream(allPostObj.toString().getBytes("UTF-8"));
InputStreamEntity entity = new InputStreamEntity(stream , -1);

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 Java UTF-8 JSON

One part of my app performs a query (via php) on a mysql database. I use in the database UTF-8 because I have letters like é à ê that need to appear.
I read through this problem because this seemed almost the same.
Android Java UTF-8 HttpClient Problem
However when I am implementing the code he replaces every return value with an é as null.
This is my code
HttpParams params = new BasicHttpParams();
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(params, "UTF-8");
params.setBooleanParameter("http.protocol.expect-continue", false);
HttpClient httpclient = new DefaultHttpClient(params);
HttpPost httppost = new HttpPost("http://www.example.com/example.php");
httppost.setEntity(new UrlEncodedFormEntity(query));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
String jsonText = EntityUtils.toString(entity, HTTP.UTF_8);
Toast.makeText(StoresInfo.this, jsonText, Toast.LENGTH_LONG).show();
is = entity.getContent();
So in the jsonText string he replaces return values with a "è" in it by null.
The last line is = entity.getConent(); I added this because I normally use the input stream to read it but this does not work as well.
Somebody has an idea?
This is my php code
<?php
mysql_select_db("database");
$q=mysql_query($_REQUEST['query']);
while($e=mysql_fetch_assoc($q))
$output[]=$e;
print(json_encode($output));
mysql_close();
?>
After trying your code on another page, I think your problem come from your server web interface.
You can for example try a GET request on a google page containing "é" characters:
HttpParams params = new BasicHttpParams();
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(params, "UTF-8");
params.setBooleanParameter("http.protocol.expect-continue", false);
HttpClient httpclient = new DefaultHttpClient(params);
HttpGet httpget = new HttpGet("http://www.google.ch/search?sourceid=chrome&ie=UTF-8&q=www.google.frb%C3%A9b%C3%A9&qscrl=1#sclient=psy&hl=fr&qscrl=1&source=hp&q=b%C3%A9b%C3%A9&aq=&aqi=&aql=f&oq=&pbx=1&fp=b4d89b2783e136eb&pf=p&pdl=300");
try
{
HttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
String jsonText = EntityUtils.toString(entity, HTTP.UTF_8);
Log.d("TEST", jsonText);
Toast.makeText(this, jsonText, Toast.LENGTH_LONG).show();
}
catch (Exception e)
{
}

Categories

Resources