How do I add UrlEncodedFormEntity to a MultipartEntityBuilder - java

I have a file that I want to upload so I have your standard MultipartEntityBuilder like this:
MultipartEntityBuilder multiPartEntity = MultipartEntityBuilder.create();
multiPartEntity.addBinaryBody("file", file);
I also have some form params that I send with the POST like this:
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("userId",userId));
postParameters.add(new BasicNameValuePair("taskId",taskId));
new UrlEncodedFormEntity(postParameters)
Both work individually, My question how do I do both in one call? I need to fold one into the other so I can make this in one HttpPost() call.

You seem to be confusing the application/x-www-form-urlencoded and multipart/form-data content types. When sending a multipart request, you are using multipart/form-data, in which case you don't need to URL encode the content. Just set the text directly
MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
multipartEntityBuilder.addBinaryBody("file", file);
multipartEntityBuilder.addTextBody("userId", "someIdWith#url$encodable<>characters");
See the specification for more details.

Related

Should I set the Content-Type header for a MultipartEntity?

I've got a small piece of code which submits an XML entity along with binary data in the same POST. I'm using the httpclient and httpmime for this.
I'm not quite sure if I should set the Content-Type header for this request. After all, the Content-Type is both application/xml and application/octet-stream.
What's the correct usage for this?
post = new HttpPost(uri);
post.setHeader("Authorization", auth);
// Should I set Content-Type at all?
post.setHeader("Content-Type", mimeType + ";charset=UTF-8");
MultipartEntityBuilder b = MultipartEntityBuilder.create();
b.addTextBody("data", payload, ContentType.APPLICATION_XML);
b.addBinaryBody("file", file);
post.setEntity(b.build());
No, you should not. You should let HttpClient generate Content-Type as well as other content metadata headers automatically based on properties of the message entity.

How to create authorization URL request with paramters

im trying to work with yahoo Gemini api
which need first to implement using Ouath 2.0
going into this link
Its saying i need to create a request to a URL with "Request Parameters"
client_id
redirect_uri
now lets say i do it in java:
this is my HTTP request:
HttpClient httpclient = HttpClients.createDefault();
HttpPost httppost = new
HttpPost("https://api.login.yahoo.com/oauth2/request_auth");
is this how i added paramters to the request ?
List<NameValuePair> params = new ArrayList<NameValuePair>(2);
params.add(new BasicNameValuePair("client_id", "ABCDEFGH"));
params.add(new BasicNameValuePair("redirect_uri", "http://www.goTo.Com"));
is this is how i execute the entire request ?
httppost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is this the currect way to Get an authorization URL and authorize access ?
is there any other way / simpler doing that ?
what should i expect in the response ?
i believe that when you're working with Yahoo Gemini, you have to use a specific couple of consumer_key/consumer_secret according to my little investigation as stated in this issue
You check the guide out for an implementation of oauth2 for yahoo apis.
Hope it helped

How to achieve the target in linux c as the java code do when I send a http post request to a server?

There is a java sample code below.It can send a http post request to a server with charset utf-8.How can I do the same thing in linux c program?
private String message = "3";
private String trading = "AAAAA";
private String document = "BBBBB";
private String targetURL = "http://10.1.2.3/param";
HttpPost httppost = new HttpPost(targetURL);
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("message", message));
params.add(new BasicNameValuePair("trading", partner));
params.add(new BasicNameValuePair("document", document));
params.add(new BasicNameValuePair("requestMessage", requestMsg));
HttpEntity request = new UrlEncodedFormEntity(params, "UTF-8");
httppost.setEntity(request);
HttpResponse httpResponse = httpclient.execute(httppost);
HttpEntity entity = httpResponse.getEntity();
String result = null;
if (entity != null) {
result = EntityUtils.toString(entity);
}
in Linux C, what http post request can achieve the same target as the java code dose?
eg.How to set the charset to utf-8
and: "message","trading","document" are in http post request's head or body?
These two questions really confuse me a lot.
Contrary to Java C doesn't come with a standard http client in its library (but then, you're using Commons HTTPClient in your Java example, also a third party library), so you have to select a third party library that implements this functionality. There are dozens to choose from, from quick and dirty to the multiprotocol all singing and dancing libcURL. On the libcURL site you'll even find a list of their competitors aka alternatives.
Which one is "best"? That depends largely on what you find important, but libcURL is well documented, and comes with a load of examples - this one especially as it's very close to what you want. Due to its popularity it will also eb a lot easier to find help in case of trouble. It even has its own tag here

Java Apache HTTPClient do not encode POST entity

I have an endpoint that requires an 'authenticity_token' that is in the format like:
Iq2rNXN+OxERv+s6TSloJfKkPZVvqnWe1m0NfODB5OI=
However, sometimes it has "special" characters, such as:
E7IzeP73OgPGgXM/up295ky1mMQMio2Nb8HMLxJFyfw=
This gets encoded to:
E7IzeP73OgPGgXM%26%2347%3Bup295ky1mMQMio2Nb8HMLxJFyfw%3D
For some reason, the endpoint does not like the encoding of those special characters and will think the token is invalid. Is it possible to add a POST variable that does not encode specific values? I am currently doing something like:
HttpPost post = new HttpPost(URL + NEW_FINDING);
List <NameValuePair> nvps = new ArrayList <NameValuePair>();
nvps.add(new BasicNameValuePair("foo", foo));
nvps.add(new BasicNameValuePair("authenticity_token", authenticityToken));
post.setEntity(new UrlEncodedFormEntity(nvps));
You can always use ByteArrayEntity or StringEntity instead of UrlEncodedFormEntity and do the encoding yourself. It should look something like foo=var1&bar=var2.
You have to set Content-Type=application/x-www-form-urlencoded
You may want to find out what your endpoint expects as a charset parameter for the application/x-www-form-urlencoded value of the Content-Type header. Then pass it as a parameter to the UrlEncodedFormEntity constructor. This should be the right fix.

Trying to HttpPost a file in Android to my server

This is roughly the code I'm working with now:
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("json", json.toString()));
nameValuePairs.add(new BasicNameValuePair("blob", file.getAbsolutePath()));
post_request.setEntity(new UrlEncodedFormEntity(nameValuePairs));
The the reply I get back from the server is good for the first add() statement but, for the second one I'm not trying to send the path, I'm trying to send the file. Taking off .getAbsolutePath() should do the trick, but It won't let me as it only accepts strings. How would I go about sending the file?
you should use a MultipartEntity, not an UrlEncodedForm one. In a Multipart body you can store objects of different mime types

Categories

Resources