Really having problem with this issue.
The below code suppose to sent to POST values (username,password) to the server and the server should just response with the var_dump of GET and POST.
PHP CODE:
var_dump($_POST);
var_dump($_GET);
ANDROID CODE:
InputStream is = null;
//http post
try{
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url + "?test=test");
httpPost.setHeader("Content-Type", "application/json");
httpPost.setHeader("Accept", "application/json");
// place them in an array list
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("username", "1123"));
nameValuePairs.add(new BasicNameValuePair("password", "123123"));
// add array list to http post
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
Log.i("Network", "POST URL: " + url);
Log.i("Network", "POST ARGS: " + jsonObj.toString());
} catch(Exception e){
Log.e("Network", "POST Error in http connection " + e.toString());
}
But all i get is:
array(0) {
}
array(1) {
["test"]=> string(4) "test"
}
I have tested the server with curl: curl -F 'username=test' http://xx.xx.xx.xx/test.php
And it gives me correct return:
array(1) {
["username"]=> string(9) "test"
}
array(0) {
}
So what am i doing wrong in the android post ?
You should not set your Content-Type header to application/json. You can either do not set the Content-Type header or set it manually to application/x-www-form-urlencoded.
Related
This question already has answers here:
How to set header in httppost/ httpget request
(2 answers)
Closed 5 years ago.
I am trying to implement a simple JSON get and post to the URL that sends token as header. Can someone help me with passing the token in header as http get and http post?
if (api.method.equals("GET")) {
try {
HttpGet httpget = new HttpGet(SERVER_URL + api.toString()+URL.replaceAll(" ","%20").trim());
//httpget.getParams().setParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, Boolean.FALSE);
httpget.setHeader("Content-type", "application/json");
httpget.setHeader("Authentication", "mytokenvalue");
//List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
//nameValuePairs.add(new BasicNameValuePair("Content-type", "application/json"));
//httpget.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
Log.d("111111111",SERVER_URL+api.toString()+URL.replaceAll(" ","%20").trim());
HttpResponse response = httpclient.execute(httpget);
return readStream(response.getEntity().getContent());
} catch (HttpHostConnectException e) {
e.printStackTrace();
}
}
HttpClient client = new DefaultHttpClient();
HttpPost request = new HttpPost(SERVER_URL
+ api.toString()+URL.replaceAll(" ","%20").trim());
request.setHeader(new BasicHeader("Content-Type","application/json"));
request.setHeader(newBasicHeader("Authorization,"token=mytokenvalue"));
response = client.execute(request);
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");
I need to send string (vietnamese) from Android devices to server like this:
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(Constants.URL.UPDATE_CURRENT_STATUS);
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("location", "Thạch thất Hanoi "));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs,
HTTP.UTF_8));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
int respnseCode = response.getStatusLine().getStatusCode();
if (respnseCode == 200) {
HttpEntity entity = response.getEntity();
return EntityUtils.toString(entity);
}
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
But when server gets the string, its not like
Thạch thất Hanoi
its become
Thạch Thất Hanoi
My code in server side:
#RequestMapping(value = "/UpdateCurrentStatus", method = RequestMethod.POST, produces = { "application/json" })
#ResponseBody
public MessageDTO updateCurrentStatus(
#RequestParam Map<String, String> requestParams) throws TNException {
String location = requestParams.get("location");
System.out.println(location);
MessageDTO result = driverBO.updateCurrentStatus(location);
return result;
}
How can I resolve this problem? Thank you.
Did you set you android httpclient Content-Type header to application/json; charset=utf-8 instead of "application/json"?
I think your problem is that the content entity location you sent is encoded correctly in UTF-8 but server failed to acknowledge UTF-8. clarify it in Content-Type header.
You can diagnose http content and its header with great http monitoring tool Fiddler.
-EDIT BELOW-
Relace your UrlEncodedFormEntity as below. Set header to application/json; charset=utf-8 as I described earlier. it's good to set it up still.
JSONObject jsonParam = new JSONObject();
jsonParam.put("location", "Thạch thất Hanoi ");
StringEntity entity = new StringEntity(jsonParam.toString(), "UTF-8");
httppost.setEntity(entity);
in my app i need to post data to an url to register a new user. Here is the url
http://myurl.com/user.php? email=[EMAIL]&username=[USERNAME]&password[PASS]&img_url=[IMG]
If I do that correctly I should get this message:
{"success":true,"error":null}
or if not {"success":false,"error":"parameters"}
Can somebody guide me through this and tell me how can I do it.
first :
you need to perform all network tasks in an Async thread using:
public class PostData extends AsyncTask<String, Void, String>{
{
#Override
protected String doInBackground(String... params) {
//put all your network code here
}
Second:
create your http request:
i am assuming email, username and IMG as variables over here.
String server ="http://myurl.com/user.php? email=[" + EMAIL + "]&username=[" + USERNAME + "]&password[" + PASS + "]&img_url=["+IMG + "]";
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(server);
//httppost.setHeader("Accept", "application/json");
httppost.setHeader("Accept", "application/x-www-form-urlencoded");
//httppost.setHeader("Content-type", "application/json");
httppost.setHeader("Content-Type", "application/x-www-form-urlencoded");
third:
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("JSONdata", Object));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs,"UTF-8"));
try {
HttpResponse response =httpclient.execute(httppost);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
Now simple query your response handler i.e. response in this case.
Don't forget to add INTERNET permission in your androidManifest.xml
Hope this helps!
Use a HTTP client class, and format your URL via a specific URI constructor. Create a HTTP post, optionally set the entity, headers, etc, execute the post via the client, receive a HTTP response, pull the entity out of the response and process it.
EDIT for example:
HttpClient httpclient = new DefaultHttpClient();
URI uri = new URI("http",
"www.google.com", // connecting to IP
"subpath", // and the "path" of what we want
"a=5&b=6", // query
null); // no fragment
HttpPost httppost = new HttpPost(uri.toASCIIString);
// have a body ?
// post.setEntity(new StringEntity(JSONObj.toString()));
// post.setHeader("Content-type", "application/json");
HttpResponse response = httpClient.execute(post);
int statusCode = response.getStatusLine().getStatusCode();
HttpEntity entity = response.getEntity();
Reader r = new InputStreamReader(entity.getContent());
// Do something with the data in the reader.
I'm currently trying to send data via POST to a server, and the server is handling the data and appends it to a JSON file. I'm currently getting a 422 error and I've been receiving it for a while now. My question is: How do I receive that JSON error itself in Java so that I can see what the error is. All I'm seeing is a HttpResponseException and it doesn't give me anything else. Thanks for the time and help in advance.
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(mPath);
// Add your data
try
{
List nameValuePairs = new ArrayList(4);
httppost.setHeader("Authorization", Base64.encodeToString(new StringBuilder(bundleId).append(":").append(apiKey).toString().getBytes("UTF-8"), Base64.URL_SAFE|Base64.NO_WRAP));
nameValuePairs.add(new BasicNameValuePair("state", "CA"));
nameValuePairs.add(new BasicNameValuePair("city", "AndDev is Cool!"));
nameValuePairs.add(new BasicNameValuePair("body", "dsads is assrawstjljalsdfljasldflkasjdfjasldjflasjdflkjaslfggddsfgfdsgfdsgfdsgfdsgfdsgfdsgfdsgfdsgfdsgfdsgfdsgfdsgfddjflaskjdfkasjdlfkjasldfkjalskdjfajasldfkasdlfjasljdflajsdfjasdjflaskjdflaksjdfljasldfkjasljdflajsasdlfkjasldfkjlas!"));
nameValuePairs.add(new BasicNameValuePair("title", "dsaghhhe fd!"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
//HttpResponse response = httpclient.execute(httppost);
//int status = response.getStatusLine().getStatusCode();
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String responseBody = httpclient.execute(httppost, responseHandler);
Log.v(TAG, "response: " + responseBody);
//JSONObject response = new JSONObject(responseBody);
int f = 0;
}
catch(HttpResponseException e)
{
Log.e(TAG, e.getLocalizedMessage());
Log.e(TAG, e.getMessage());
e.printStackTrace();
}
you may send your parameters more conveniently by using predefined Json class as below:
String jsonParam = null;
try{
JSONObject param = new JSONObject();
param.put("state", "CA");
param.put("city", "AndDev is Cool!");
//and so on with other parameters
jsonParam = param.toString();
}
catch (Exception e) {
// TODO: handle exception
}
and set the post entity as:
if(jsonParam != null)
httppost.setEntity(new StringEntity(jsonParam, HTTP.UTF_8));
422 error says: Unprocessable Entity - The request was well-formed but was unable to be followed due to semantic errors
You got a problem with UrlEncodedFormEntity