how to post data using JSON for httpPost in Android - android

I have an example json as below:
{
"Passwd":"String content",
"Userme":"String content"
}
how to construct the JSON String as above and give it as argument to HttpPost in Android.?
Can anyone help me in sorting out this issue.
thanks in Advance,

You can make use of JSONObject to create a simple json like { "Passwd":"String content", "Userme":"String content" } try something like this.
String json="";
JSONObject jobj = new JSONObject();
jobj.put("Userme", "Username");
jobj.put("Passwd", "PasswordValue");
json = jobj.toString();
Above String can be sent as one of the parameter using HTTP POST easily. Below function takes url and json as parameters to make POST request.
private void httpPost(String json,String url) throws ClientProtocolException, IOException{
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(2);
nameValuePair.add(new BasicNameValuePair("json", json));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));
httpClient.execute(httpPost);
}

Related

Cant send json to server

I'm trying to send a json file to remote server. If I try it, using this site:
https://www.hurl.it/ passing a json like this:
it works. But If I try it from my code, I have some trouble.
ArrayList<NameValuePair> nameValuePairs1 = new ArrayList<NameValuePair>();
JSONArray list1 = new JSONArray();
list1.add("12345678");
Map obj=new LinkedHashMap();
obj.put("company_id","1");
obj.put("phones", list1);
obj.put("name","Alexy");
obj.put("birthdate","12.03.2014");
obj.put("email","nesalexy#mail.ru");
nameValuePairs1.add(new BasicNameValuePair("json", obj.toString()));
try {
URL url = new URL("http://crm.pavlun.info/api/register");
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url.toURI());
httpPost.setEntity(new StringEntity(nameValuePairs1.toString(), "UTF-8"));
httpPost.setHeader("Content-Type", "application/json");
httpPost.setHeader("Accept-Encoding", "application/json");
HttpResponse response = httpClient.execute(httpPost);
Log.e("r ", response.toString());
}catch(Exception e) {
e.printStackTrace();
}
This is my json example: I need to create something like this: "json":{"company_id":"1","phones":["555555"],"photo":"/files/clients_photos/tmp/484629825.JPG","name":"sdfsdfdsf","birthdate":"10.02.2014", "email":"sdf#sdf.ff"}
UPD:
I have the following error:
{"status":"error","message":"Customer data is empty!"}
Maybe something is wrong in my json.
UDP:
working code
ArrayList<NameValuePair> nameValuePairs1 = new ArrayList<NameValuePair>();
JSONObject joB = new JSONObject();
JSONArray list1 = new JSONArray();
list1.add("258963147");
Map obj=new LinkedHashMap();
obj.put("company_id","1");
obj.put("phones", list1);
obj.put("name","Alexy");
obj.put("birthdate","12.03.2014");
obj.put("email","nesalexy#mail.ru");
org.json.JSONObject jsonqwe;
try {
JSONParser operationLink = new JSONParser();
ArrayList<NameValuePair> postP = new ArrayList<NameValuePair>();
postP.add(new BasicNameValuePair("json", JSONValue.toJSONString(obj)));
jsonqwe = operationLink.makeHttpRequest("http://crm.pavlun.info/api/register", "POST", postP);
Log.e("sad", jsonqwe.toString());
}catch(Exception e) {
e.printStackTrace();
}
You're problem is that you're not building a JSON object, but using the map's toString() method, which won't give you a properly formatted JSON object.
Try JSONObject's constructor that takes a map as parameter. And than call toString() on the JSONObject.
Try yo change
Map obj=new LinkedHashMap();
to
JSONObject obj=new JSONObject();
you need to send a JSON value
A more suitable solution would be to build a JSONObject instead of the Map you're using. Something like this:
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
JSONArray phoneNumbers = new JSONArray();
phoneNumbers.add("12345678");
JSONObject obj=new JSONObject();
obj.put("company_id","1");
obj.put("phones", phoneNumbers);
obj.put("name","Alexy");
obj.put("birthdate","12.03.2014");
obj.put("email","nesalexy#mail.ru");
nameValuePairs.add(new BasicNameValuePair("json", obj.toString()));
try {
URL url = new URL("http://crm.pavlun.info/api/register");
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url.toURI());
httpPost.setEntity(new StringEntity(nameValuePairs.toString(), "UTF-8"));
httpPost.setHeader("Content-Type", "application/json");
httpPost.setHeader("Accept-Encoding", "application/json");
HttpResponse response = httpClient.execute(httpPost);
Log.e("r ", response.toString());
}catch(Exception e) {
e.printStackTrace();
}
This line will return garbage (as far server is concerned)
nameValuePairs1.toString()
because an ArrayList does implement toString like you are expecting. You should be using JSONArray/JSONObject instead.
In the hurl site example one name valu pair is sent. To send name value pais your content type should be form url encoded. So change:
httpPost.setHeader("Content-Type", "application/json");
httpPost.setHeader("Accept-Encoding", "application/json");
to
httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");
Maybe this will help:
httpPost.setHeader("ENCTYPE","multipart/form-data");
EDIT:
As others already stated do not use a Map but a JSONObject. Then change
httpPost.setEntity(new StringEntity(nameValuePairs1.toString()));
to:
String nameValuPairsText = nameValuePairs.toString();
nameValuPairsText = nameValuPairsText.substring(1, nameValuPairsText.length()-1);
httpPost.setEntity(new StringEntity(nameValuPairsText, "UTF-8"));

how to post json format data to server

How to post JSON data to .net server?
can i use:
httpClient = new DefaultHttpClient();
httpPost = new HttpPost(URL);
List<NameValuePair> pairs = new ArrayList<NameValuePair>();
pairs.add(new BasicNameValuePair("Code", Code));
pairs.add(new BasicNameValuePair("Subject", Subject));
httpPost.setEntity(new UrlEncodedFormEntity(pairs));
httpResponse=httpClient.execute(httpPost);
or any other format to send json data?
You can create JSON Object and Put data into that object and pass it to the server..
use,
JSONObject json = new JSONObject();
json.put("UserName", "test2");
json.put("FullName", "1234567");
to put data into json object...
use
json.toString(); to send the data and
request.setHeader(HTTP.CONTENT_TYPE, "application/json");
to mark the json format...
Refer these links for more:
Send and Receive Json android-php
Sending json from Android
Here is the solution after referring many sources...
protected Void doInBackground(Void... params) {
httpClient = new DefaultHttpClient();
httpPost = new HttpPost(URL);
httpPost.setHeader("Content-Type", "application/json");
JSONObject jsonObject = new JSONObject();
jsonObject.put("Code", Code);
jsonObject.put("Subject", Subject);
stringEntity = new StringEntity(jsonObject.toString());
stringEntity.setContentEncoding("UTF-8");
stringEntity.setContentType("application/json");
httpPost.setEntity(stringEntity);
httpResponse=httpClient.execute(httpPost);
return null;
}
protected void onPostExecute(Void result) {
//to see the response
httpEntity=httpResponse.getEntity();
Response=EntityUtils.toString(httpEntity);
System.out.println("Response "+Response);
int Response_Code = httpResponse.getStatusLine().getStatusCode();
System.out.println("Response_Code "+Response_Code);
}
Thanks for your response, also helped me find this.
You can add one more parameter to the URL named json(or any name you want), and use the json string as value and then get the json in your php.
example:
pairs.add(new BasicNameValuePair("Code", Code));
pairs.add(new BasicNameValuePair("Subject", Subject));
pairs.add(new BasicNameValuePair("Json", my_jsons_tring));

Post Parameters in Android Request

I am doing an Android application and I have a problem doing my request against my own server. I have made the server with Play Framework, and I get the parameters from a Json:
response.setContentTypeIfNotSet("application/json; charset=utf-8");
JsonParser jsonParser = new JsonParser();
JsonElement jsonElement = jsonParser.parse(getBody(request.body));
Long id =jsonElement.getAsJsonObject().get("id").getAsLong();
When I make my GET request against my server, all is ok. But when I make a POST request, my server return me an unknown error, something about there is a malformed JSON or that it is unable to find the element.
private ArrayList NameValuePair> params;
private ArrayList NameValuePair> headers;
...
case POST:
HttpPost postRequest = new HttpPost(host);
// Add headers
for(NameValuePair h : headers)
{
postRequest.addHeader(h.getName(), h.getValue());
}
if(!params.isEmpty())
{
postRequest.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
}
executeRequest(postRequest, host);
break;
I have tried to do with the params of the request, but it was a failure:
if(!params.isEmpty())
{
HttpParams HttpParams = new BasicHttpParams();
for (NameValuePair param : params)
{
HttpParams.setParameter(param.getName(), param.getValue());
}
postRequest.setParams(HttpParams); }
And there is the different errors, depends on the request I make. All of them are 'play.exceptions.JavaExecutionException':
'com.google.gson.stream.MalformedJsonException'
'This is not a JSON Object'
'Expecting object found: "id"'
I wish somebody can help me.
Here is a simple way to send a HTTP Post.
HttpPost httppost = new HttpPost("Your URL here");
httppost.setEntity(new StringEntity(paramsJson));
httppost.addHeader("content-type", "application/json");
HttpResponse response = httpclient.execute(httppost);
You would be better off using the JSON String directly instead of parsing it here. Hope it helps
Try this,It may help u
public void executeHttpPost(String string) throws Exception
{
//This method for HttpConnection
try
{
HttpClient client = new DefaultHttpClient();
HttpPost request = new HttpPost("URL");
List<NameValuePair> value=new ArrayList<NameValuePair>();
value.add(new BasicNameValuePair("Name",string));
UrlEncodedFormEntity entity=new UrlEncodedFormEntity(value);
request.setEntity(entity);
client.execute(request);
System.out.println("after sending :"+request.toString());
}
catch(Exception e) {System.out.println("Exp="+e);
}
}

Android POST JSON OBJECT - How to set $_POST Index

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

Android Webview POST

I am trying to accomplish something quite simple, yet I have found no good documentation on this. I have a webView, and I need to load a page in it that requires POST data. Seems like a simple process, yet I cannot find a way to display the result in a webView.
The process should be simple:
query(with POST data) -> webserver -> HTML response -> WebView.
I can submit data using a DefaultHttpClient, but this cannot be displayed in a WebView.
Any suggestions?
Much Thanks
Solution
private static final String URL_STRING = "http://www.yoursite.com/postreceiver";
public void postData() throws IOException, ClientProtocolException {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("foo", "12345"));
nameValuePairs.add(new BasicNameValuePair("bar", "23456"));
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(URL_STRING);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
String data = new BasicResponseHandler().handleResponse(response);
mWebView.loadData(data, "text/html", "utf-8");
}
Two ways to load post response in webview:
webview.loadData(): Like what you have posted in your solution. But "content loaded through this mechanism does not have the ability to load content from the network".
webview.postUrl(): Use this if post response needs to load content from the network. (NOTE: only accessible from api-level 5, which means no android 1.6 or lower)
String postData = "username=my_username&password=my_password";
webview.postUrl(url,EncodingUtils.getBytes(postData, "BASE64"));
(source: http://www.anddev.org/other-coding-problems-f5/webview-posturl-postdata-t14239.html)
Try this:
private static final String URL_STRING = "http://www.yoursite.com/postreceiver";
public void postData() throws IOException, ClientProtocolException {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("foo", "12345"));
nameValuePairs.add(new BasicNameValuePair("bar", "23456"));
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(URL_STRING);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
}
I would recommend doing this as part of an AsyncTask and updating the WebView afterwards
I use webView.loadData() to do client post, and it will display content of url, my code :
public static void webview_ClientPost(WebView webView, String url, Collection< Map.Entry<String, String>> postData){
StringBuilder sb = new StringBuilder();
sb.append("<html><head></head>");
sb.append("<body onload='form1.submit()'>");
sb.append(String.format("<form id='form1' action='%s' method='%s'>", url, "post"));
for (Map.Entry<String, String> item : postData) {
sb.append(String.format("<input name='%s' type='hidden' value='%s' />", item.getKey(), item.getValue()));
}
sb.append("</form></body></html>");
webView.loadData(sb.toString(), "text/html", "UTF-8");
}
use function webview_ClientPost() :
Map<String, String> mapParams = new HashMap<String, String>();
mapParams.put("param1", "111");
mapParams.put("param2", "222");
Collection<Map.Entry<String, String>> postData = mapParams.entrySet();
webview_ClientPost(webView1, "http://www.yoursite.com/postreceiver", postData);
If you use a WebView from the start could it work?
A Webview with a html/js that does the POST, and naturally displays the result.
You can also pass post key:value pair in JSON format to web view.
String userName = "admin";
String password = "Admin#2021";
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("userName", userName);
jsonObject.put("password", password);
} catch (JSONException e) {
e.printStackTrace();
}
String url = "http://www.example.com";
webView.postUrl(url, jsonObject.toString().getBytes());

Categories

Resources