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))
Related
Probably duplicate question but I couldn't find an answer for my problem. I have this code to call a web service:
var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://172.21.122.1:5001/autocomplete");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
//tried this too: httpWebRequest.Accept = "gzip, deflate";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
streamWriter.Write("{ \"message\" : \"mü\" }");
streamWriter.Flush();
streamWriter.Close();
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
response = "";
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
response = streamReader.ReadToEnd();
}
But no matter what Encoding I tried with StreamReader() c'tor, I get this response or worse: {"words":["m\u00fc\u015fteri","m\u00fc\u015fterisiyim""]}
When I use Postman or SoapUI to call the same service with the same request: {"message": "mü"},
response looks ok: {"words": ["müşteri","müşterisiyim"]}
Strange thing is: The same code works OK with many other services. It is only this specific service that the reponse is not correctly encoded. We believe there is a programming error with the service, but what I wonder is how Postman or SoapUI handles this. There should be a control in their code and if the response contains "\uxxxx", then Postman or SoapUI decodes it again.
I've checked all request / response headers in Postman and SoapUI with no luck. What can be the reason?
You have to make sure that your request is encoded correctly:
Set the Content Type to:
httpWebRequest.ContentType = "application/json;charset=UTF-8";
Check if request body is also UTF-8 encoded. Set the StreamWriter encoding to UTF-8 as well:
...
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream(), Encoding.UTF8))
...
If you are getting the request content from other source, make sure to read it also using UTF-8 encoding.
Regex.Unescape(response) worked like a charm, thanks JosefZ!
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
I am trying to consume a (GET) rest service.
http://localhost:7010/abc/status?configFilePath=config%2Fconfig.properties
I am trying to use that using the Spring RestTemplate service
Below is the code which I have used for the restTemplate:
String configFile = "config/config.properties";
Map<String,String> restvars = new HashMap<String,String>();
restvars.put("configFilePath", configFile);
RestTemplate restTemplate = new RestTemplate();
String restUrl = http://localhost:7010/abc/status?
String restCall = restTemplate.getForObject(restUrl, String.class, restvars);
System.out.println(restCall.toString());
It throws
Required String parameter 'configFilePath' is not present
Doesn't the Map actually pass the parameters ?
I was looking at it from wrong angle. The answer from this SO question helped.
HttpHeaders headers = new HttpHeaders();
headers.set("Accept", MediaType.APPLICATION_JSON_VALUE);
UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url)
.queryParam("configFilePath", configFile);
HttpEntity<?> entity = new HttpEntity<>(headers);
HttpEntity<String> response = restTemplate.exchange(builder.toUriString(),String.class);
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
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);