HttpClient httpclient = new DefaultHttpClient();
try {
HttpPost httpMethod = new HttpPost(this.transformURL(request));
BasicHttpParams params = new BasicHttpParams();
params.setParameter("name", name);
httpMethod.setParams(params);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
httpclient.execute(httpMethod, responseHandler);
}catch{
LOG.error("Error");
} finally {
httpclient.getConnectionManager().shutdown();
}
I have the above code, and I'm trying to pass in a name variable as a paramter to get picked up in another method by request.getParameter("name").
It doesn't seem to be working, when I debug I can see the parameters get set but when I follow it through to the next method that gets executed, it doesn't pick up the parameters.
Any suggestions?
EDIT:
I added this and it worked great
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("name", request.getParameter("name")));
httpMethod.setEntity(new UrlEncodedFormEntity(nameValuePairs));
Did you check this example? it uses the class BasicNameValuePair instead of BasicHttpParams as you do.
Also, the documentation for the version 3.x of HttpClient does it:
PostMethod post = new PostMethod("http://jakarata.apache.org/");
NameValuePair[] data = {
new NameValuePair("user", "joe"),
new NameValuePair("password", "bloggs")
};
post.setRequestBody(data);
// execute method and handle any error responses.
...
InputStream in = post.getResponseBodyAsStream();
// handle response.
Update: The BasicHttpParams class is an implementation of the HttpParams interface, which as #Perception notes below, is a set of properties "that customize the behavior of the HTTP client". From the HttpParams javadoc: "HttpParams is expected to be used in 'write once - read many' mode. Once initialized, HTTP parameters are not expected to mutate in the course of HTTP message processing."
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 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 use Apache's DefaultHttpClient() with the execute(HttpPost post) method to make a http POST.
With this I log on to a website.
Then I want to use the same Client to make a HttpGet.
But when I do, I get an Exception:
Exception in thread "main" java.lang.IllegalStateException: Invalid use of SingleClientConnManager: connection still allocated.
I am not sure as to why this occurs. Any help would be appreciated.
public static void main(String[] args) throws Exception {
// prepare post method
HttpPost post = new HttpPost("http://epaper02.niedersachsen.com/epaper/index_GT_neu.html");
// add parameters to the post method
List <NameValuePair> parameters = new ArrayList <NameValuePair>();
parameters.add(new BasicNameValuePair("username", "test"));
parameters.add(new BasicNameValuePair("passwort", "test"));
UrlEncodedFormEntity sendentity = new UrlEncodedFormEntity(parameters, HTTP.UTF_8);
post.setEntity(sendentity);
// create the client and execute the post method
HttpClient client = new DefaultHttpClient();
HttpResponse postResponse = client.execute(post);
//Use same client to make GET (This is where exception occurs)
HttpGet httpget = new HttpGet(PDF_URL);
HttpContext context = new BasicHttpContext();
HttpResponse getResponse = client.execute(httpget, context);
// retrieve the output and display it in console
System.out.print(convertInputStreamToString(postResponse.getEntity().getContent()));
client.getConnectionManager().shutdown();
}
This is because after the POST, the connection manager is still holding on to the POST response connection. You need to make it release that before you can use the client for something else.
This should work:
HttpResponse postResponse = client.execute(post);
EntityUtils.consume(postResponse.getEntity();
Then, you can execute your GET.
I'm trying to add a referer to an http post in Apache HttpClient (httpclient-4.0-beta2).
I found some sample code that does this. The code works, but I'm wondering if there is not a simpler, more straightforward way to add the referer than using the (ominously named) addRequestInterceptor, which appears to take an (yikes!) inner class as a parameter.
The code in question begins below with "// add the referer header". I'm a novice, and this code is doing several things that I don't understand. Is this really the simplest way to add a referer to my http post?
Thanks for any pointers.
// initialize request parameters
List<NameValuePair> formparams = new ArrayList<NameValuePair>();
formparams.add(new BasicNameValuePair("firstName", "John"));
formparams.add(new BasicNameValuePair("lastName", "Doe"));
// set up httppost
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, "UTF-8");
HttpPost httppost = new HttpPost(submitUrl);
httppost.setEntity(entity);
// create httpclient
DefaultHttpClient httpclient = new DefaultHttpClient();
// add the referer header, is an inner class used here?
httpclient.addRequestInterceptor(new HttpRequestInterceptor()
{
public void process(final HttpRequest request,
final HttpContext context) throws HttpException, IOException
{
request.addHeader("Referer", referer);
}
});
// execute the request
HttpResponse response = httpclient.execute(httppost);
Any reason not to do:
httppost.addHeader("Referer", referer);
? HttpPost subclasses (indirectly) AbstractHttpMessage so you should be able to just add headers that way.