setting params and multipart entity in HttpClient - httpclient

I using HttpClient and httpost to upload my image file along with some parameters.
My code looks like
HttpClient httpclient = new DefaultHttpClient();
HttpPost httpost = new HttpPost("xyz.com");
ArrayList<NameValuePair> postParameters;
postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("name","Temp"));
postParameters.add(new BasicNameValuePair("id","12345"));
httpost.setEntity(new UrlEncodedFormEntity(postParameters));
MultipartEntity entity = new MultipartEntity();
File imgFile = new File("C:\test.img");
FileBody imgFileBody = new FileBody(imgFile);
entity.addPart("multipartcontent", imgFileBody); //No i18n
httpost.setEntity(entity);
HttpResponse httpResponse = httpclient.execute(httpost);
Am not getting the param values in server. Am i doing anything wrong. Please guide me.

httpost.setEntity(new UrlEncodedFormEntity(postParameters));
...
httpost.setEntity(entity);
The multipart entity overrides the URL encoded one completely discarding its content.
You should add param values to the multipart entity as one or several body parts

Related

Handle French Char in Response while getting using REST Template Spring Boot

I have below piece of code:
**RestTemplate restTemplate = new RestTemplate(getClientHttpRequestFactory());
restTemplate.getMessageConverters().add(0, new StringHttpMessageConverter(StandardCharsets.UTF_8));
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
HttpEntity<?> requestObject = new HttpEntity<>(request,headers);
ResponseEntity<String> result = restTemplate.postForEntity(uri, requestObject, String.class);**
Now we are getting french char like 'Numéro'. while getting response in result variable it became 'Num�ro' .. I need same as we have in response ('Numéro').
Try setting content type in headers.
headers.setAccept(new ArrayList(MediaType.APPLICATION_JSON))

How to consume stream response body using Apache HC

I am using a REST API, which returns continouous real-time streaming response body. The response body stream is opening continuously. I want to read this streamed response through Apache Http Components.
Any help is appreciated.
[UPDATE]
My response is similar to this demo
https://github.com/brianhempel/stream_json_demo
You have to set up a client to send and recieve stream response from API.
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("http://localhost/something");
post.setHeader("Referer", "http://localhost/something");
post.setHeader("Authorization", "Basic (with a username and password)");
post.setHeader("Content-type", "application/json");
// if you need any parameters
List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
urlParameters.add(new BasicNameValuePair("paramName", "paramValue"));
post.setEntity(new UrlEncodedFormEntity(urlParameters));
HttpResponse response = client.execute(post);
HttpEntity entity = response.getEntity();
Header encodingHeader = entity.getContentEncoding();
// you need to know the encoding to parse correctly
Charset encoding = encodingHeader == null ? StandardCharsets.UTF_8 :
Charsets.toCharset(encodingHeader.getValue());
// use org.apache.http.util.EntityUtils to read json as string
String json = EntityUtils.toString(entity, StandardCharsets.UTF_8);
JSONObject o = new JSONObject(json);
You can get apache HTTP client library from here http://hc.apache.org/ and commons-io

Upgrading POST request from HttpClient to HttpComponents. What's going wrong here?

I inherited some old code that uses the now-deprecated Apache Commons HttpClient. I was tasked with upgrading it to use the newer Apache HttpComponents. However, I can't seem to get this POST request to function properly. The server keeps complaining that Content-Length = 0. I'm fairly certain that it's a problem with my conversion of how parameters are added.
The old HttpClient code looks something like this:
PostMethod postMethod = null;
int responseCode = 0;
try{
HttpClient httpClient = new HttpClient();
postMethod = new PostMethod(getServiceUrl()); //The url, without a query.
...
postMethod.addParameter(paramName, request);
responseCode = httpClient.executeMethod(postMethod);
...
}
And here are my HttpComponents replacements:
HttpPost postMethod = null;
int responseCode = 0;
HttpResponse httpResponse = null;
try{
HttpClient httpClient = new DefaultHttpClient();
postMethod = new HttpPost(getServiceUrl()); //The url, without a query.
...
BasicHttpParams params = new BasicHttpParams();
params.setParameter(paramName, request);
postMethod.setParams(params);
httpResponse = httpClient.execute(postMethod);
responseCode = httpResponse.getStatusLine().getStatusCode();
...
}
The servlet my code it talking to is using Apache Commons FileUpload. Here is the code it catches on when it receives my request:
ServletRequestContext src = new ServletRequestContext(request);
if (src.getContentLength() == 0)
throw new IOException("Could not construct ServletRequestContext object");
It used to pass this test just fine. Now it doesn't. I've tried all kinds of alternatives, such as using the header, or passing request as a URLEncoded query. Have I made a mistake in my upgrade, somewhere?
Note: I can't just change how the servlet receives my request, because then I'll have to change a number of other apps that talk to it, and that's too big a job.
To set the request body, you can use HttpPost's setEntity() method. You can explore the available entity types here. This would replace the BasicHttpParams code.
To send a form entity, for example:
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://someurl");
List<NameValuePair> formParams = new ArrayList<NameValuePair>();
formParams.add(new BasicNameValuePair("name", "value"));
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(formParams, "UTF-8");
httpPost.setEntity(formEntity);
HttpResponse httpResponse = client.execute(httpPost);

ServiceStack on server and .NET Compact Framework client

I created my server and clients (MonoDroid and Windows) with ServiceStack, everything works very well, but now I need to consume the data from the server with a mobile client with Compact Framework F3.5.
I can access it as SOAP webservice, but I would prefer to go through REST, and use a framework to simplify things, just like the ServiceStack client (that as RestSharp is not compatible with the Compact Framework).
Do you know of something compatible with CF3.5 that lets me connect with a ServiceStack server in an easy way as
var client = new JsonServiceClient("http://192.168.0.87:82");
HelloResponse response = client.Get(new Hello { Name = "World!" });
UPDATE:
I managed to get the response with HTTPWebRequest and deserialize my HelloResponse object with an old JSON.Net version that supports the .NET Compact Framework.
The only thing that I'm missing is how to serialize my hypothetical HelloReq object and pass it to the HttpWebRequest, any hint? (without having to manually create the route as below)
HttpWebRequest req = (HttpWebRequest)WebRequest.Create("http://192.168.0.87:82/Hello/test?format=json");
req.Method = "GET";
HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
Stream respStream = resp.GetResponseStream();
string resps;
using (var reader = new StreamReader(respStream, Encoding.UTF8))
{
resps = reader.ReadToEnd();
}
respStream.Close();
JsonTextReader jreader = new JsonTextReader(new StringReader(resps));
JsonSerializer serializer = new JsonSerializer();
HelloResponse p = serializer.Deserialize<HelloResponse>(jreader);
Thanks!
Request created:
HttpWebRequest req = (HttpWebRequest)WebRequest.Create("http://192.168.0.87:82/json/syncreply/Hello");
req.ContentType = "text/json";
req.Method = "POST";
req.ContentLength = json.Length;
using (var streamWriter = new StreamWriter(req.GetRequestStream()))
{
streamWriter.Write(json);
streamWriter.Flush();
streamWriter.Close();
}

How to call a GwtServiceImpl Servlet from external application?

I have developed a Gwt application and need now to call its remote service implementation
from another java application. Is there a method that given a List of Java Objects can transform them in a format suitable for invoking the get service servlet?something like:
myObject = .......
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost postRequest = new HttpPost(
"http://localhost:8080/ppp//org.yournamehere.Main/gwtservice");
String serialized = <somelibrary.serialize>(myObject);
StringEntity input = new StringEntity(serialize);
input.setContentType("text/x-gwt-rpc; charset=UTF-8");
postRequest.setEntity(input);
HttpResponse response = httpClient.execute(postRequest);
Although, I haven't tried it the following link seems to be what you are looking for
http://googlewebtoolkit.blogspot.com/2010/07/gwtrpccommlayer-extending-gwt-rpc-to-do.html