I have a POST method in the server side, which get a JSON (as raw text) and some headers. The response is data (a file content), which send by the server to the client.
I search for a way to write the client in Java. The client sends a POST message with raw text, and some headers, and know to get the response.
All the example I saw use the HttpsURLConnection, but I didn't see any way to send the raw text (JSON), and get the data content.
Perhaps something like this could help ?
(Using org.apache.httpcomponents:httpcore:4.3.2)
HttpEntity reqEntity = MultipartEntityBuilder.create()
.addPart("query", new InputStreamBody(rawData, "rawData.xml"))
.build();
HttpPost httppost = new HttpPost(serverUrl);
httppost.addHeader("SomeHeader", "SomeValue");
httppost.setEntity(reqEntity);
HttpClient httpclient = HttpClientBuilder.create().build();
HttpResponse response = httpclient.execute(httppost);
int statusCode = response.getStatusLine().getStatusCode();
InputStream os = response.getEntity().getContent();
...
Related
I have a RESTful API that I can call by doing the following:
curl -H "Content-Type: application/json" -d '{"url":"http://www.example.com"}' http://www.example.com/post
In Java, when I print out the received request data from the cURL, I correctly get the following data:
Log: Data grabbed for POST data: {"url":"http://www.example.com/url"}
But when I send a POST request via Java using HttpClient/HttpPost, I am getting poorly formatted data that does not allow me to grab the key-value from the JSON.
Log: Data grabbed for POST data: url=http%3A%2F%2Fwww.example.com%2Furl
In Java, I am doing this:
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.example.com/post/");
List<BasicNameValuePair> nameValuePairs = new ArrayList<BasicNameValuePair>();
BasicNameValuePair nvp1 = new BasicNameValuePair("url", "http://www.example.com/url);
nameValuePairs.add(nvp1);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse httpresponse = httpclient.execute(httppost);
How do I make it so that the request from Java is similar to cURL in terms of how the data is sent?
The data you present as coming from the Java client are URL-encoded. You appear to specifically request that by using a UrlEncodedFormEntity. It is not essential for the body of a POST request to be URL-encoded, so if you don't want that then use a more appropriate HttpEntity implementation.
In fact, if you want to convert generic name/value pairs to a JSON-format request body, as it seems you do, then you probably need either to use a JSON-specific HttpEntity implementation or to use a plainer implementation that allows you to format the body directly.
I'm doing a GET request with version 4.3.3 of Apache HttpClient, like this:
HttpGet httpGet = new HttpGet("http://www.revenue.ie/en/tax/it/forms/med1.pdf");
CloseableHttpClient client = HttpClients.createDefault();
CloseableHttpResponse response = client.execute(httpGet);
client.close();
The response status code tells me 200, and the content length as returned by response.getEntity().getContentLength() is 1213954, but the InputStream as returned from a call to:
response.getEntity().getContent()
...is reporting 0 bytes available.
I have been successfully making GET calls like this to retrieve and parse the HTML of other URLs, but is there something different I need to do here since it's file contents that I'm interested in?
The problem was that I was closing the http client too early i.e. client.close() before I tried to retrieve the response InputStream with a call to response.getEntity().getContent().
I'm writing a network android application that uses http requests to get data. The data is HTML format. I use Apache HttpClient and JSoup.
When I'm out of traffic with my mobile internet provider, I am always redirected to the providers' page saying that I should pay some money. Of course, it is a bad idea to parse this page.
How to detect occured page substitution?
This code will help you to know with is the final target of your request, if isn't the page that you asked for, is the provider page.
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpGet httpget = new HttpGet("http://www.google.com/");
HttpResponse response = httpclient.execute(httpget, localContext);
HttpHost target = (HttpHost) localContext.getAttribute(
ExecutionContext.HTTP_TARGET_HOST);// this is the final page of the request
System.out.println("Final target: " + target);
HttpEntity entity = response.getEntity();
EntityUtils.consume(entity);
Thanks
If your provider is lying to you by immediately returning a 200 OK but not giving you the resource you've requested, your best option is probably to set a custom HTTP response header that your client can check before continuing.
I am suppose to send song (mp3/wav) file and some data through secure restful web service. I am using MultipartEntity to make HttpPost request. but When I execute it through HttpClient, the server replies this error
HTTP Status 400 - Bad Request
type: Status report
message : Bad Request
The request sent by the client was syntactically incorrect (Bad Request).
But the service is doing very well if we call it from its Web interface. please help
its the code
HttpClient httpclient = new DefaultHttpClient();
HttpPost postRequest = new HttpPost();
try {
MultipartEntity reqEntity = new MultipartEntity();
reqEntity.addPart("email", new StringBody("test#testmail.com"));
reqEntity.addPart("password", new StringBody("123"));
reqEntity.addPart("title", new StringBody("My new song"));
reqEntity.addPart("musicData", new FileBody(new File(FilePath)));
// FIlePath is path to file and contains correct file location
postRequest.setEntity(reqEntity);
postRequest.setURI(new URI(ServiceURL));
HttpResponse response = httpclient.execute(postRequest);
} catch (URISyntaxException e) {
Log.e("URISyntaxException", e.toString());
}
I also included apache-mime4j, httpclient, httpcore and httpmime jars for MultipartEntity.
This is HTML page snap for the Service.
Try removing the setURI method and passing the URL in when you create your HttpPost object, as follows. This worked for me (more here).
HttpClient httpclient = new DefaultHttpClient();
HttpPost postRequest = new HttpPost(ServiceURL);
try {
MultipartEntity reqEntity = new MultipartEntity();
reqEntity.addPart("email", new StringBody("test#testmail.com"));
reqEntity.addPart("password", new StringBody("123"));
reqEntity.addPart("title", new StringBody("My new song"));
reqEntity.addPart("musicData", new FileBody(new File(FilePath)));
postRequest.setEntity(reqEntity);
HttpResponse response = httpclient.execute(postRequest);
} catch (URISyntaxException e) {
Log.e("URISyntaxException", e.toString());
}
It seems header of the request is incorrect, this problem can occur if you use a different Auth protocol or upper/lower case or simply wrong things in header that server side can't handle.
Dont waste your time by trying different different combinations.There are some HTTP Request tools available for HTTP with which you can track request and response you are getting.Ex. HTTP Analyzer download trial version
Call URL from your working webinterface , copy request and response
then do same with from program the tool is enogh capable to capture your request and response data.
Now compare working and non working request you will surely able to dignose the issue whether it can be header issue or some authentication related issue.
I'm using DefaultHttpClient to make an http connection. I [think] we can set the preferred locale in the http headers [http accept-language] when making a connection, which the server can check and send back content in a matching language (if it wants).
Anyone know if this is possible, or how to go about doing this with DefaultHttpClient?
Thanks
You have to add your header to HttpRequest object
HttpClient client = new DefaultHttpClient();
HttpPost request = new HttpPost(URL);
request.addHeader("Accept-Language", "en");
HttpResponse response = client.execute(request);