I am posting data in json Format to server but I am getting response status 404,
please let me know how to fixed,
JSONObject jsonObject = new JSONObject();
jsonObject.accumulate("email", uemail);
// 4. convert JSONObject to JSON to String
json = jsonObject.toString();
Log.e("value send",json);
StringEntity se = new StringEntity(json.toString());
// 6. set httpPost Entity
httpPost.setEntity(se);
// 7. Set some headers to inform server about the type of the content
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
// 8. Execute POST request to the given URL
HttpResponse httpResponse = httpclient.execute(httpPost);
// 9. receive response as inputStream
inputStream = httpResponse.getEntity().getContent();
thanks
Related
I am developing an Android app with a NodeJS backend server. I am having problems authenticating the users when requests are made to different pages after the user is logged in.
Once I log in, i store the set-cookie value in SharedPrefs. Now when I make a POST request, I am sending the set-cookie value in the header, i.e. con.setRequestProperty("set-cookie", cookie); for authenticating the user on the backend using req.user.authenticate.
However, req.user is undefined and hence the request fails. What could be wrong over here? Thanks.
Below is my POST request code.
con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", "\"Mozilla/5.0\"");
con.setDoOutput(true);
JSONObject jsonParam = new JSONObject();
try {
jsonObject.accumulate("set-cookie", cookie);
} catch (JSONException e) {
e.printStackTrace();
}
OutputStreamWriter out = new OutputStreamWriter(con.getOutputStream());
out.write(jsonParam.toString());
out.close();
int responseCode = con.getResponseCode();
System.out.println("Response Code:"+responseCode);
Send data in this format
String data = "";
InputStream inputStream = null;
try{
JSONObject jsonObject = new JSONObject();
jsonObject.accumulate("set-cookie", cookie);
data = jsonObject.toString();
Log.d("json data",data);
// 1. create HttpClient
HttpClient httpclient = new DefaultHttpClient();
// 2. make POST request to the given URL
HttpPost httpPost = new HttpPost(CHECK_WEBSERVICE_URL);
StringEntity se = new StringEntity(data);
// 6. set httpPost Entity
httpPost.setEntity(se);
// 7. Set some headers to inform server about the type of the content
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
// 8. Execute POST request to the given URL
HttpResponse httpResponse = httpclient.execute(httpPost);
// 9. receive response as inputStream
inputStream = httpResponse.getEntity().getContent();
// 10. convert inputstream to string
if(inputStream != null)
result = convertInputStreamToString(inputStream);
else
result = "Did not work!";
System.out.print(result);
}catch (Exception e){
e.printStackTrace();
}
I'm using ASP Web API web service which is hosted on SmarterAsp.net to get data in Json format to use them in my android application, when I use Wifi everything works fine and the Json is received correctly but when I use mobile data I get com.google.gson.JsonSyntaxException while parsing the Json received, I checked the received Json string with the debugger and it was malformed and here is what i received :
��������������RMo�#�+՞)��Sڦ9TjeU�)�aX�x\��Ah"�{b�����̾y3OL�G�Y�İ�u²"���r'��J V�#�����(���
���(N9*4MĜ���Fר��m+
���:�7[�/$3��z����c�%q*Ha�OA|�x~������G�8���"?,�4���(��y���N��j�L%���?B
�?S8�lp���(G�rgH�����P�b9����+5��<�n����w_i�G-,��_؋��uz�K;��|�i������� ��|6s����V[J�<�%3���X�������
And here is the method I'm using in android to send and receive data from the ASP Web API web service :
public String PostObject(String url, Object obj) throws IOException {
DefaultHttpClient client = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
StringEntity stringEntity = new StringEntity(new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ss").create().toJson(obj));
httpPost.setEntity(stringEntity);
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
httpPost.setHeader("Accept-Encoding", "gzip");
HttpResponse httpResponse = client.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
String rep = EntityUtils.toString(httpEntity);
return rep;
}
It is not malformed. You are accepting gzip compressed data by declaring ("Accept-Encoding", "gzip") in the header.
You can either remove the compression or decompress the data and then use it.
On how to decompress
I want to perform following task :
1 > accept input from user and save it
2 > Send this input value with whole json object to server
This is log cat result
see this
http://hmkcode.com/android-send-json-data-to-server/
How to send a JSON object over Request with Android?
USe The following code..
// 1. create HttpClient
HttpClient httpclient = new DefaultHttpClient();
// 2. make POST request to the given URL
HttpPost httpPost = new HttpPost(url);
String json = "";
// 3. build jsonObject
JSONObject jsonObject = new JSONObject();
jsonObject.accumulate("name", person.getName());
jsonObject.accumulate("country", person.getCountry());
jsonObject.accumulate("twitter", person.getTwitter());
// 4. convert JSONObject to JSON to String
json = jsonObject.toString();
// ** Alternative way to convert Person object to JSON string usin Jackson Lib
// ObjectMapper mapper = new ObjectMapper();
// json = mapper.writeValueAsString(person);
// 5. set json to StringEntity
StringEntity se = new StringEntity(json);
// 6. set httpPost Entity
httpPost.setEntity(se);
// 7. Set some headers to inform server about the type of the content
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
// 8. Execute POST request to the given URL
HttpResponse httpResponse = httpclient.execute(httpPost);
// 9. receive response as inputStream
inputStream = httpResponse.getEntity().getContent();
i have a JSONObject which i want to POST to a server.
Here is the Code:
JSONObject obj = new JSONObject();
for(int k = 0; k<len;k++){
obj.put("nachrichten_ids", params[k]);
}
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("xxxxx");
HttpEntity entity;
StringEntity s = new StringEntity(obj.toString());
s.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
entity = s;
httpPost.setEntity(entity);
HttpResponse response;
response = httpClient.execute(httpPost);
By doing Log.i("TEST",obj) i get the JSON object:
{"nachrichten_ids":"[2144,2138]"}
That data is send to the server. But i cant access it:
There is no $_POST index. (PHP)
How to set a index, so that i can access the json object, like $_POST['nachrichten_ids'].
I had to work with that data then e.g with php json_decode()
Any idea ?
Thanks
Try putting your jSON object into a namevaluepair. The name of the pair you add is the name you should use when reading it on the web. For example here I will get Password by calling $_POST['Password'].
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("Password", "My password"));
nameValuePairs.add(new BasicNameValuePair("Mail", "My mail"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
BasicHttpResponse response = (BasicHttpResponse) httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
I'm trying to perform a POST request to a server that wants the Content-Type set to application/json with name and email as some keys. Currently, I'm getting a 406 error, which I'm assuming is working on the server side, but android can't handle the response. How can I tweak the code to get a 200 response?
HttpClient client = new DefaultHttpClient();
HttpEntity entity;
try{
JSONObject j = new JSONObject();
j.put("name" , myName);
j.put("email", myEmail);
HttpPost post = new HttpPost(targetURL);
post.setHeader("Content-Type", "application/json");
StringEntity se = new StringEntity(j.toString(), HTTP.UTF_8);
se.setContentType("application/json");
post.setEntity(se);
HttpResponse response = client.execute(post);
entity = response.getEntity();
Log.d("response", response.getStatusLine().toString());
} catch(Exception e){Log.e("exception", e.toString());}
Does that look about right? Do I need one of those response handlers when creating the HttpClient?
This works for me with json-2.0.jar
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), MyApplication.HTTP_TIMEOUT); //Timeout Limit
HttpResponse response;
ArrayList<appResults> arrayList = new ArrayList<appResults>();
String resul;
try{
HttpGet get = new HttpGet(urls[0]);
response = client.execute(get);
/*Checking response */
if(response!=null){
InputStream in = response.getEntity().getContent(); //Get the data in the entity
resul = convertStreamToString(in);
Gson gson = new Gson();
Type listType = new TypeToken<ArrayList<appResults>>() {}.getType();
arrayList = gson.fromJson(resul, listType);
in.close();
of course in asynctask or thread.
But 406... it seems that your format on your webserver and your app are not consistent...