Hi iam creating an android application. In my application i have some form fields like edittext and radio buttons i am creating a JSONObject by retrieving text from all the form fields. JsonObject is created successfully. Now i want to pass this object to my PHP page where i have written code for getting this details and storing it in database. My problem is i am not understanding how to send this JSON object through httpPost or httpGet method. Only way i know is send parameters through List<NameValuePair> so i'm trying to convert JSONObject to List<NameValuePair>. Can anybody provide a method which can directly convert my JSONObject to List<NameValuePair>. Is there any predefined method for doing this. Or can any one provide solution where i can directly send by JSONObject to PHP and retrieve there.
Pass your JSONObject as a string to the String Entity constructor and then pass it to setEntity()
Sample:
HttpPost request = new HttpPost("//website");
StringEntity params =new StringEntity("passmyjson=" + yourJSONOBject.toString());
request.addHeader("content-type", "//header");
request.setEntity(params);
HttpResponse response = httpClient.execute(request);
in php File to check that it works;
<?php
print_r($_POST);
$json_string = $_POST['passmyjson'];
$json = json_decode($json_string);
print_r($json);
?>
You can do that with Apache HttpClient. I assume you have already a PHP handler that handles this request. Simply,
Create your JSONObject
Put your desired values
Send that json to php handler
You need to send request as application/x-www-form-urlencoded
Let's call url : http://your_php_service.com/handleJson;
HttpClient httpClient = new DefaultHttpClient();
JSONObject json = new JSONObject();
json.put("key", "val");
try {
HttpPost request = new HttpPost("http://your_php_service.com/handleJson");
StringEntity params = new StringEntity("json=" + json.toString());
request.addHeader("content-type", "application/x-www-form-urlencoded");
request.setEntity(params);
HttpResponse response = httpClient.execute(request);
} catch (Exception ex) {
} finally {
httpClient.getConnectionManager().shutdown();
}
The format of request param will be ;
json={"key": "val"}
And you can handle this on php side like;
<?php
.....
$json = $_POST["json"]; // This will be json string
.....
Thank you all i got it
I added the following lines to my android Activity class
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpResponse httpResponse;
HttpPost httppost = new HttpPost(link); //-->link is the php page url
httppost.setEntity(new StringEntity(obj.toString())); //-->obj is JSONObject
httpResponse = httpClient.execute(httppost);
HttpEntity httpEntity = httpResponse.getEntity();
and in my php file i have added the following code
$msg=json_decode(file_get_contents('php://input'), true);
To get particular value from recieved Json string i added this $data = $msg['name'] ;
It is working
Related
So I've got this code:
HttpClient httpClient = new DefaultHttpClient();
try {
HttpPost request = new HttpPost("url");
StringEntity params = new StringEntity("stuff");
request.addHeader("content-type", "application/json");
//request.addHeader("Accept","application/json");
request.setEntity(params);
HttpResponse response = httpClient.execute(request);
//stuff
} catch (Exception ex) {
//stuff
} finally {
httpClient.getConnectionManager().shutdown();
}
I need to create a POST request which I can do with curl -X POST /groups/:group_id/members/add etc but I'm not sure how to add the /groups/ param to my code... I'm not super familiar with how to do this so any advice would be appreciated. Thanks!
EDIT 1: (SOLVED)
Have used the suggested code but would like some help with variables used in the string while remaining valid JSON format, if possible.
EDIT 2:
Using that method, can you show an example of how to add multiple users to that one StringEntity? So like user1 is "User1" and has the email "Email1" and user2 has "User2" and "Email2" etc
Just create a url string using the prams you have and pass it as argument to HttpPost()
DefaultHttpClient httpClient = new DefaultHttpClient();
String groupId = "groupId1";
String URL = "http://localhost:8080/"+groupId+"/members/add"
HttpPost postRequest = new HttpPost(
URL );
StringEntity input = new StringEntity("{\"name\":matt,\"from\":\"stackovefflow\"}");
input.setContentType("application/json");
postRequest.setEntity(input);
HttpResponse response = httpClient.execute(postRequest);
UPDATED
The input to StringEntity is a string whihc you can manipulate in any way.
You can define a method like
private createStringEntity(String name, String email){
return new StringEntity("{\"name\":\""+name+"\",\"email\":\""+email+"\"}");
}
The "/groups/..." part is not a parameter but a fraction of the url. I dont think this will work, because "url" is just a String, change it to this:
HttpPost request = new HttpPost("http://stackoverflow.com/groups/[ID]/members/add");
i'm trying to send json object from java client to C# WebApi, but the input parameter is null.
the java code:
ObjectMapper mapper = new ObjectMapper();
Gson gson = new Gson();
String json = gson.toJson(per);
HttpClient httpclient = new DefaultHttpClient();
List<NameValuePair> qparams = new ArrayList<NameValuePair>();
qparams.add(new BasicNameValuePair("person", json.toString()));
HttpGet httpPost = new HttpGet("http://naviserver.azurewebsites.net/api/Person/Get?" + URLEncodedUtils.format(qparams, "UTF-8"));
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
httpPost.setHeader(
"Authorization",
"Bearer TokenRemovedBecauseUseless");
org.apache.http.HttpResponse httpResponse = httpclient.execute(httpPost);
the WebApi method:
public List<String> Get([FromUri]Person person)
{}
can someone tell me how to send json object?
The problem is that the WebApi is not expecting the person object in JSON format. By using FromUri with a complex object, it is expecting that the url with have a query parameter for each field in Person.
There is a nice example here about how it works.
Basically you will want your query parameters to look like this:
http://naviserver.azurewebsites.net/api/Person/Get?name=dave&age=30
and in Java:
qparams.add(new BasicNameValuePair("name", person.getName()));
qparams.add(new BasicNameValuePair("age", String.valueOf(person.getAge())));
If you want to send the person in JSON format, a better way would be to use a HTTP POST and set the JSON in the body. Then in the WebApi, your method would look like this:
public HttpResponseMessage Post([FromBody]Person person)
You will then also have to change your Java client to send a POST request.
HttpClient httpClient = HttpClientBuilder.create().build();
HttpPost httpPost = new HttpPost("http://naviserver.azurewebsites.net/api/Person");
Person person = new Person("dave", 30);
Gson gson = new Gson();
String json = gson.toJson(person);
StringEntity body = new StringEntity(json);
httpPost.setEntity(body);
HttpResponse response = httpClient.execute(httpPost);
I'm using the following code to send a http request to github.
String url = "https://api.github.com/repositories";
try {
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
HttpPost request = new HttpPost(url);
// StringEntity params = new StringEntity(body);
request.addHeader("content-type", "application/json");
// request.setEntity(params);
HttpResponse result = httpClient.execute(request);
String json = EntityUtils.toString(result.getEntity(), "UTF-8");
System.out.println(json);
} catch (IOException ex) {
}
I got output: {"message":"Not Found","documentation_url":"https://developer.github.com/v3"}
If use directly put "https://api.github.com/repositories" in browser, a lot of useful information will be shown. My question is how can I get the information I see when using browser by using Java.
You should use HttpGet instead of HttpPost. Just like your browser sends a GET request.
I'm currently working on a project which needs to send a post request and get a json object from the server. Earlier I used Get method to access the json object. It worked fine. But because of some server changes I had to move to post method. Then it doesn't return me the json object that I got earlier from the 'get' method. I tried my best to come up with a solution but couldn't. Highly appreciate if anyone can help me to get through this problem.
private AdSniperAdObjectResponse postData(String url) {
//Bundle b = new Bundle();
HttpClient httpClient = HttpClientFactory.getThreadSafeClient();
//Log.d(TAG, "url: " + url);
try {
HttpPost httpPost = new HttpPost(url);
httpPost.setHeader("Content-Type", "application/json");
httpPost.setHeader("Accept", "JSON");
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(4);
nameValuePairs.add(new BasicNameValuePair("latitude", "-33.8736"));
nameValuePairs.add(new BasicNameValuePair("longitude", "151.207"));
nameValuePairs.add(new BasicNameValuePair("age", "35"));
nameValuePairs.add(new BasicNameValuePair("gender", "All"));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity resEntity = httpResponse.getEntity();
if (resEntity != null) {
String resp = EntityUtils.toString(resEntity);
Above is the code that I use. Earlier I used HttpGet class. For HttpPost, the 'resp'variable is always null. Don't know what I did wrong.
should't this be like
HttpResponse httpResponse = httpClient.execute(httpPost);
if (httpResponse != null) {
String resp = httpResponse.toString();
and in case if server return JSONString..
say JSONObject data = new JSONObject(resp);
and then get values..
DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(typeof (List<NameValuePair> ));
try with this and pass your data using this
jsonSerializer.WriteObject(reqStream, nameValuePairs );
reqStream.Close();
and again deserialize the response whatever you are getting
Before you attempt to get the HttpEntity, you should get the StatusLine and check that the status code is what you expect. I suspect that the real problem is that the server is sending an error response of some kind. And since you used an "Accept" header to request a JSON response, it is likely that the server is not sending any diagnostics in the response body ... so it is empty.
Guys I found the solution. It worked when I commented the following two lines.
httpPost.setHeader("Content-Type", "application/json");
httpPost.setHeader("Accept", "JSON");
So thanks everyone for your answers. Highly appreciate.
I have code for POST query on Java
ArrayList<HashMap<String, String>> books=SQLiteDbWrapper.getInstance().getAllBooks();
JSONObject object=new JSONObject();
object.put("key", KEY);
JSONArray isbns=new JSONArray();
for (HashMap<String, String> book:books) {
isbns.put(book.get(SQLiteDbHelper.ISBN13_FIELD));
}
object.put("isbns", isbns);
object.put("email", email);
Log.e("log", object.toString());
HttpClient client = new DefaultHttpClient();
HttpPost request = new HttpPost(BASE_URL+SUBMIT_SCRIPT);
request.setEntity(new ByteArrayEntity(
object.toString().getBytes("UTF8")));
HttpResponse response = client.execute(request);
I need to send JSON data into server; my web-service must get this data from $POST['json'] variable, but I don't know how can I put my JSONObject object into 'json' field for POST query? Please, help me
You must do as follows:
String jsonValue = object.toString();
String encoded = java.net.URLEncoder.encode(jsonValue, "UTF-8");
List<NameValuePair> formData = new ArrayList<NameValuePair>();
formData.add(new NameValuePair("json", encoded));
request.setHeader("Content-Type", "application/x-www-form-urlencoded");
request.setRequestBody(formData);
response = client.execute(request);
Your code looks OK. All I see is a missing content type in the HttpPost object.
request.setHeader("Content-Type", "application/json");