HttpPost view post params - java

I'd like to be able to view the complete HttpClient / HttpPost URI with params. I'm not sure how to output it to my console.
HttpClient httpclient = HttpClients.createDefault();
HttpPost httppost = new HttpPost(url);
httppost.setHeader("ContentType","application/x-www-form-urlencoded");
httppost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
System.out.println(httppost.getURI());
Printing getURI only outputs the baseURI and not the params.
Could someone help me with what I'm missing?

The entity has a method to serialize itself to an output stream writeTo(), so you can create one and dump the entity there. This is not the whole request, only the UrlEncodedFormEntity exposing the encoded parameters:
ByteArrayOutputStream outs = new ByteArrayOutputStream();
httppost.getEntity().writeTo(outs);
System.out.println(outs.toString("UTF-8"));
outs.close();
result is one line like this:
foul=play&foo=bar&baz=bam

Related

How to encode Post Data JSON in CloseableHttpClient APi

I have used the CloseableHttpClient APi for a Post call and Basic Auth for authorisation
private CloseableHttpClient httpclient = HttpClients.createDefault();
HttpPost httppost = new HttpPost("https://example.com");
MyJson myJson = new MyJson(); //custom java object to be posted as Request Body
Gson gson = new Gson();
String param = gson.toJson(myJson);
StringEntity urlparam = new StringEntity(param);
String credentials = username + ":" + passwprd;
String base64Credentials = new String(Base64.getencoder().encode(credentials.getBytes()));
String authorizartionHeader = "Basic" + base64Credentials;
httppost.setHeader("Content-Type", "application/Json");
httppost.setHeader("Authorization", authorizartionHeader);
urlparam.setContentEncoding("UTF-8");
httppost.setEntity(urlparam);
httpclient.execute(httppost);
I am getting error
"Invalid UTF-8 middle byte"
I have encoded the JSON still the encoding is not working for other locales except English. How to encode the Post data.
I tried using the method
httppost.setEntity(new URLEncodedFormEntity(namevaluePair, "UTF-8")) but I don't have any Namevaluepair and if the add the Username-pswd in that then getting Null pointer response.
You should try to set everything as UTF-8
StringEntity urlparam = new StringEntity(param, StandardCharsets.UTF_8);
And add proper header
httppost.setHeader("Content-Type", "application/json;charset=UTF-8");

HttpPost return a empty body

I have the code below, and my problem is that the response.status is 200 (is ok) and my response body is empty and it should return a json response. Is the problem the length maybe?:`
HttpPost post = new HttpPost("http://localhost:8080/rest/login");
httpClient = HttpClients.createDefault();
List<NameValuePair> formParams = new ArrayList<NameValuePair>();
NameValuePair pair = new BasicNameValuePair("token",token);
formParams.add(pair);
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formParams);
post.setEntity(entity);
HttpResponse response = httpClient.execute(post);
this.code = response.getStatusLine().getStatusCode();
InputStream body = response.getEntity().getContent();
BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));`
I had similar problem. In my case it was also very strange, that when url contained IP instead of hostname, it worked (I get the nonempty response).
However, setting netscape cookie specs helped in my case.
httpClientBuilder.setDefaultRequestConfig(RequestConfig.custom()
.setCookieSpec(CookieSpecs.NETSCAPE)
.build());

Posting to REST api using Java, specifically Android

I'm posting to the Wufoo api inside of an Android app and I am hitting a bit of a snag. My data does not seem to be formatting in a way that the server likes (or there is some other issue). Here is my code (note authkey and authpass are placeholders in the exmaple):
HttpClient httpclient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
String json = "";
JSONObject jsonObject = new JSONObject();
jsonObject.accumulate("Field17", "Some Value");
json = jsonObject.toString();
StringEntity postData = new StringEntity(json, "UTF8");
httpPost.setEntity(postData);
String authorizationString = "Basic " + Base64.encodeToString(
("authkey" + ":" + "authpass").getBytes(),
Base64.NO_WRAP);
httpPost.setHeader("Content-type", "application/json");
httpPost.setHeader("Authorization", authorizationString);
HttpResponse httpResponse = httpclient.execute(httpPost);
inputStream = httpResponse.getEntity().getContent();
The response I get back from the server looks like this:
{"Success":0,"ErrorText":"Errors have been <b>highlighted<\/b> below.","FieldErrors":
[{"ID":"Field17","ErrorText":"This field is required. Please enter a value."}]}
This is the response for a failure (obviously) which leads me to believe I'm doing the authentication correctly, and that it just doesn't like my JSON string, I've looked through the API docs which are located here:
http://www.wufoo.com/docs/api/v3/entries/post/
and by all accounts this should work? Any suggestions?
I would start by looking at this line:
StringEntity postData = new StringEntity(json, "UTF8");
It's "UTF-8", not "UTF8".
Note: I would suggest you using the HTTP.UTF_8 constant in order to avoid this kind of problem again.
StringEntity postData = new StringEntity(json, HTTP.UTF_8);
The Field17 may be of specific field type other than string.
After reading the document, I think you missed the point. The server accepted fields parameter from http post, not from a json string.
Your problem looks like this one.
So your request should like this:
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("Field17", "Some Value"));
httpPost .setEntity(new UrlEncodedFormEntity(postParameters));
Hope this can help.
I actually figured this out, this isn't a problem with the code anyone here gave me, it's the fact that I was sending the wrong header info. This must be a quirk of the Wufoo API.
If I use the BasicNameValuePair objects like what was suggestion by R4j and I remove the line
httpPost.setHeader("Content-type", "application/json");
everything works perfectly!
Thanks for all the help and I hope this helps anyone who is having trouble with the Wufoo API and Java.

In Java, how can I HttpPost only the contents of a protocol buffer?

I've tried using a ByteArrayEntity, as below, but this sends extra bytes that aren't in the protocol buffer itself. Is there an Entity which just POSTs the contents?
byte [] info;
... [info initialized] ...
HttpPost httppost = new HttpPost("https://myurl");
ByteArrayEntity reqEntity = new ByteArrayEntity(info);
reqEntity.setContentType("binary/octet-stream");
reqEntity.setChunked(true);
httppost.setEntity(reqEntity);
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
The answer is disappointingly banal: the extra bytes were added by the call to setChunked(true). Removing the call results in only the bytes in "info" getting sent.

Where do I put the REST Client Authentication Data in the Query?

I need to work with REST api in android application which is created by my client. Below text is just copied from the pdf the client provides us.
--
In this example, a new user is created.
The parts of a possible request to the server is shown below:
Message part Contents
Header POST {url-prefix}/rest/user
Content-Type: application/xml
Content-Length: 205
Body <request>
<client>
<id>XY</id>
<name>myName</name>
<password>myPassword</password>
</client>
<user>
<name>myUserName</name>
<password>myUserPassword</password>
<groupId>12345</groupId>
</user>
</request>
--
After searching and studying, I come to know that, the possible request code (in Java) might be:
URL url=new URL("http://api.example.com/rest/user/?name=myUserName&password=myUserPassword&groupId=12345");
HttpURLConnection conn=(HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("Post");
OutputStreamWriter out=new OutputStreamWriter(conn.getOutputStream());
out.write("respose content:");
out.close();
From the pdf manual they provide, I got to know, for every request to the server, the client (thats me) has to transmit the authentication data.
My question is, where do I put the authentication data in the query string? Please help me on this.
Edit:After posting the below code as request:
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://api.example.com/rest/user/?name=Foysal&password=123456&groupid=12345");
httpPost.addHeader("Accept", "text/xml");
httpPost.setHeader("Content-Type","application/xml;charset=UTF-8");
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("name", "APIappDevAccount"));
nameValuePairs.add(new BasicNameValuePair("password", "123456"));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpParams params = new BasicHttpParams();
HttpConnectionParams.setStaleCheckingEnabled(params, false);
HttpConnectionParams.setConnectionTimeout(params, 5000);
HttpConnectionParams.setSoTimeout(params, 5000);
httpClient.setParams(params);
httpClient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.RFC_2109);
HttpResponse response = httpClient.execute(httpPost);
InputStream is = response.getEntity().getContent();
ByteArrayOutputStream os = new ByteArrayOutputStream();
byte[] buf;
int ByteRead;
buf = new byte[1024];
String xmldata = null;
double totalSize = 0;
while ((ByteRead = is.read(buf, 0, buf.length)) != -1) {
os.write(buf, 0, ByteRead);
totalSize += ByteRead;
}
xmldata = os.toString();
os.close();
is.close();
But I got the response as:
404
Not Found
Not Found The requested
URL /rest/user/ was not found on this
server. Apache/2.2.6
(Fedora) DAV/2 mod_ssl/2.2.6
OpenSSL/0.9.8b Server at
api.example.com Port 80
Looks to me like they want you to POST an XML document and put the authentication in that. Not much of a REST API (most REST APIS don't require an XML document).
You need to use conn.getOutputStream() to send that doc to the server and use conn.getInputStream() to read the response.
So you would have to create the XML doc like the one they show:
<request>
<client>
<id>XY</id>
<name>myName</name>
<password>myPassword</password>
</client>
<user>
<name>myUserName</name>
<password>myUserPassword</password>
<groupId>12345</groupId>
</user>
</request>
And then send it in your POST:
conn.setRequestProperty ( "Content-Type", "text/xml" );
out.write(requestDoc); //where requestDoc is the String containing the XML.
out.flush();
out.close();
You may execute a POST request like shown here: http://www.androidsnippets.com/executing-a-http-post-request-with-httpclient and put the authentication data as name value pairs:
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.yoursite.com/script.php");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("name", "myUserName"));
nameValuePairs.add(new BasicNameValuePair("password", "myUserPassword"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
} catch (Exception e) {
// ... handle exception here
}

Categories