How to make POST request with Spring-android without key-value parametrs - java

I can do this with android functions:
I have post parametrs like JsonString:
String parametrs = "{\"object\": \"parametr\"};
And then im setting connection, creating String entity and makingRequest:
String url = "http://lalala.com/json/";
HttpPost request = new HttpPost(url);
StringEntity se = null;
...
se = new StringEntity(parametrs, "UTF-8");
...
request.setEntity(se);
String jsonString = null;
HttpParams httpParameters = new BasicHttpParams();
...
HttpClient httpClient = new DefaultHttpClient(httpParameters);
try
{
HttpResponse response = httpClient.execute(request);
......
How can i do this thing with spring?

you could use:
String parametrs = "{\"object\": \"parametr\"}";
RestTemplate restTemplate = new RestTemplate();
template.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
restTemplate.put(new URI("http://lalala.com/json/"), parametrs);
It is the same result on server (I test it with Google App Engine + Spring MVC).
But maybe you should think about a Jackson libery, so you would be able to send Objects =)
I use:
jackson-annotations-2.4.1.jar
jackson-core-2.4.1.jar
jackson-databind-2.4.1.1.jar
spring-android-core-1.0.0.RELEASE.jar
spring-android-rest-template-1.0.1.RELEASE.jar
Jackson downloadable here
So you would be able to send it like:
restTemplate.put(new URI(http://lalala.com/json/), new Example(1L, "test");
By the way: the above code doesn't use the params, it uses the body to send the information.
Hope I was able to help you.
Let's try again and again and ...

Related

Java JSON Apache POST Parameters

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

add json object to Java HttpGet request to C# WebApi

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

Use Java to get Github repositories

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.

Method to convert JSONObject to List<NameValuePair>

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

How to POST JSON request using Apache HttpClient?

I have something like the following:
final String url = "http://example.com";
final HttpClient httpClient = new HttpClient();
final PostMethod postMethod = new PostMethod(url);
postMethod.addRequestHeader("Content-Type", "application/json");
postMethod.addParameters(new NameValuePair[]{
new NameValuePair("name", "value)
});
httpClient.executeMethod(httpMethod);
postMethod.getResponseBodyAsStream();
postMethod.releaseConnection();
It keeps coming back with a 500. The service provider says I need to send JSON. How is that done with Apache HttpClient 3.1+?
Apache HttpClient doesn't know anything about JSON, so you'll need to construct your JSON separately. To do so, I recommend checking out the simple JSON-java library from json.org. (If "JSON-java" doesn't suit you, json.org has a big list of libraries available in different languages.)
Once you've generated your JSON, you can use something like the code below to POST it
StringRequestEntity requestEntity = new StringRequestEntity(
JSON_STRING,
"application/json",
"UTF-8");
PostMethod postMethod = new PostMethod("http://example.com/action");
postMethod.setRequestEntity(requestEntity);
int statusCode = httpClient.executeMethod(postMethod);
Edit
Note - The above answer, as asked for in the question, applies to Apache HttpClient 3.1. However, to help anyone looking for an implementation against the latest Apache client:
StringEntity requestEntity = new StringEntity(
JSON_STRING,
ContentType.APPLICATION_JSON);
HttpPost postMethod = new HttpPost("http://example.com/action");
postMethod.setEntity(requestEntity);
HttpResponse rawResponse = httpclient.execute(postMethod);
For Apache HttpClient 4.5 or newer version:
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost("http://targethost/login");
String JSON_STRING="";
HttpEntity stringEntity = new StringEntity(JSON_STRING,ContentType.APPLICATION_JSON);
httpPost.setEntity(stringEntity);
CloseableHttpResponse response2 = httpclient.execute(httpPost);
Note:
1 in order to make the code compile, both httpclient package and httpcore package should be imported.
2 try-catch block has been ommitted.
Reference:
appache official guide
the Commons HttpClient project is now end of life, and is no longer
being developed. It has been replaced by the Apache HttpComponents
project in its HttpClient and HttpCore modules
As mentioned in the excellent answer by janoside, you need to construct the JSON string and set it as a StringEntity.
To construct the JSON string, you can use any library or method you are comfortable with. Jackson library is one easy example:
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
ObjectMapper mapper = new ObjectMapper();
ObjectNode node = mapper.createObjectNode();
node.put("name", "value"); // repeat as needed
String JSON_STRING = node.toString();
postMethod.setEntity(new StringEntity(JSON_STRING, ContentType.APPLICATION_JSON));
I use JACKSON library to convert object to JSON and set the request body like below. Here is full example.
try (CloseableHttpClient httpclient = HttpClients.createDefault()) {
HttpPost httpPost = new HttpPost("https://jsonplaceholder.typicode.com/posts");
Post post = new Post("foo", "bar", 1);
ObjectWriter ow = new ObjectMapper().writer();
String strJson = ow.writeValueAsString(post);
System.out.println(strJson);
StringEntity strEntity = new StringEntity(strJson, ContentType.APPLICATION_JSON);
httpPost.setEntity(strEntity);
httpPost.setHeader("Content-type", "application/json");
try (CloseableHttpResponse response = httpclient.execute(httpPost)) {
System.out.println(response.getCode() + " " + response.getReasonPhrase());
HttpEntity entity = response.getEntity();
String result = EntityUtils.toString(entity);
System.out.println(result);
EntityUtils.consume(entity);
} catch (ParseException e) {
e.printStackTrace();
}
} catch (IOException e) {
System.out.println(e.getMessage());
}

Categories