How to add URL parameters from a NameValuePair to the HttpPost request - java

I am trying to make a request to a webApi url, u have written the following code and i have my parameters in a NameValuePair object.
Now i don't know how to add these parameters to the base uri do i have to do it manually by concatenating strings? or is there any other way, please help.
private static final String apiBaseUri="http://myapp.myweb.com/path?";
private boolean POST(List<NameValuePair>[] nameValuePairs){
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(apiBaseUri);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs[0]));
HttpResponse response = httpclient.execute(httppost);
String respond = response.getStatusLine().getReasonPhrase();
Log.d("MSG 3 > ",respond);
return true;
}

you can use this to add the parameters to the url
nameValuePairs.add(new BasicNameValuePair("name",value));
String UrlString = URLEncodedUtils.format(nameValuePairs, "utf-8");
url +=UrlString;

Related

How do contents in name value pair pass as arguments in Android Studio?

Suppose i have this
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("pin", "date"));
And When i use the following code
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://X.X.X.X/abcdef.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
what will be the post request? How will the arguments pass in the url?
found the answer
can refer this link for more details
arguments are passed as this
http://localhost/xyz.php?pin=date&package=123&requirements=xxx&last_date=25%20april

Unable to make http POST request in java?

static HttpClient httpclient = new DefaultHttpClient();
static HttpPost httppost = new HttpPost("http://servername:6405/biprws/logon/long");
public static void main(String[] args) throws ClientProtocolException, IOException {
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("userName", "Administrator"));
postParameters.add(new BasicNameValuePair("password", "test"));
postParameters.add(new BasicNameValuePair("auth", "secEnterprise"));
httppost.setEntity(new UrlEncodedFormEntity(postParameters));
httppost.addHeader("accept", "application/json");
httppost.addHeader("Content-Type", "application/json");
HttpResponse response = httpclient.execute(httppost);
Header s = response.getFirstHeader("logontoken");
String s1 = s.getValue();
System.out.println(s1);// null pointer exception here
}
Running the code above i am not able to add request body to the POST request. How can i achieve this?
Alternative method i followed:
HttpClient client1 = new DefaultHttpClient();
HttpPost post = new HttpPost("http://servername:6405/biprws/logon/long");
String json = "{\"UserName\":\"Administrator\",\"Password\":\"test\",\"Auth\":\"secEnterprise\"}";
StringEntity entity = new StringEntity(json,"UTF-8");
entity.setContentType("application/json");
post.setEntity(entity);
System.out.println(entity);
post.setHeader("Accept", "application/json");
HttpResponse response = client1.execute(post);
BufferedReader rd1 = new BufferedReader(
new InputStreamReader(response.getEntity().getContent()));
String result1 = null;
String line1 = "";
result1 = rd1.readLine();
System.out.println(result1);
Still i am not able to make request.
You are successfully receiving a response which does not contain the "logontoken" header. Very possibly because the response is not an HTTP 200 OK response. Why? We don't know, it all depends on the protocol that your server implements on top of HTTP.
That having been said, the use of both httppost.setEntity(new UrlEncodedFromEntity(postParameters)) and httppost.addHeder("Content-Type", "application/json") does not look right to me. A URL-encoded form entity is not of json content type. So, either convert your post parameters to json, or lose the content-type header.

apache http client send url encoded post request

I have a dropwizard service in whitch i implemented a post request who consumes APPLICATION_FORM_URLENCODED media type and uses #FormParam annotation
Then in my client i'm using Apache HttpClient to make a post request like this:
public void sendPost(String path, JsonObject params) throws Exception {
String url = "http://" + TS_API_HOST + ":" + TS_API_PORT + "/" + path;
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(url);
httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
Iterator<String> keys = params.keySet().iterator();
while(keys.hasNext()){
String currentKey = keys.next();
nvps.add(new BasicNameValuePair(currentKey, params.get(currentKey).toString()));
}
System.out.println(nvps.toString());
httpPost.setEntity(new UrlEncodedFormEntity(nvps));
CloseableHttpResponse response = httpClient.execute(httpPost);
try {
System.out.println(response.getStatusLine());
HttpEntity entity2 = response.getEntity();
// do something useful with the response body
// and ensure it is fully consumed
EntityUtils.consume(entity2);
} finally {
response.close();
}
}
The url and params I'm passing are correct but i keep getting 400 bad request as a response.
In Postman it works very well...

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

Adding parameter to HttpPost on Apache's httpclient

I am trying to set some Http parameters in the HttpPost object.
HttpPost post=new HttpPost(url);
HttpParams params=new BasicHttpParams();
params.setParameter("param", "value");
post.setParams(params);
HttpResponse response = client.execute(post);
It looks like the parameter is not set at all. Do you have any idea why this is happening?
Thank you
For those who hopes to find the answer using HttpGet, here's one (from https://stackoverflow.com/a/4660576/330867) :
StringBuilder requestUrl = new StringBuilder("your_url");
String querystring = URLEncodedUtils.format(params, "utf-8");
requestUrl.append("?");
requestUrl.append(querystring);
HttpClient httpclient = new DefaultHttpClient();
HttpGet get = new HttpGet(requestUrl.toString());
NOTE: This doesn't take in consideration the state of your_url : if there is already some parameters, if it already contains a "?", etc. I assume you know how to code/search and will adapt regarding your case.
HttpPost httpPost = new HttpPost(url);
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
nvps.add(new BasicNameValuePair("param", "value"));
httpPost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
httpClient.execute(httpPost);

Categories