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
Related
While trying to Create a new Document in my IrisCouch Database, i am always getting following error:
{"error":"bad_request","reason":"invalid_json"}
This is the relevant part of my function:
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("https://username.iriscouch.com:6984/mydb");
StringEntity entity = new StringEntity(body);
httpPost.setEntity(entity);
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
HttpResponse httpResponse = httpClient.execute(httpPost);
System.out.println(httpResponse.toString()) ;
HttpEntity httpEntity = httpResponse.getEntity();
// Get the response
BufferedReader rd = new BufferedReader(new InputStreamReader(httpEntity.getContent()));
String line = "";
while ((line = rd.readLine()) != null) {
System.out.println(line);
}
System.out.println("body: " + body);
} catch (Exception e) {
e.printStackTrace();
}
Here is my System.out of "body":
{"bild1":"","bild2":"","bild3":"","bild4":"","bild5":"","bild6":"","bild7":"","bild8":"","bild9":"","bild10":"","name":"","plz":0,"ort":"","strasse":"","n_koordinate":0,"e_koordinate":0,"beschreibung":"","groesse":"< 50m²","sitzplaetze":"< 50","grillstellen":"1","reservierung":false,"res_name":"","res_tele":"","res_weiteres":"","wc":true,"behindi":false,"dach":true,"kinderfreundl":false,"auto":false,"kinderwagen":false,"einkauf":false,"datum":"2015-07-01-14:12:01:856","bewertung":0,"anz_bewertung":0}
The JSON is valid. Tested it with jsonlint.com JSON Validator.
What could i do? Thanks in advance!
Perhaps the unicode superscript 2 (²) is bothering it?
Not sure which library this HttpPost is, but seems a lot like the HttpWebRequest, so try setting your header this way:
httpPost.setHeader("Content-type", "application/json charset=utf-8");
It could also be that the HttpPost class doesn't properly encode strings.
(I haven't pasted this in my Visual studio, so just a shot in the dark)
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");
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/
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());
}
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.