Apache http post example - java

I am very new to this Apache http client. I have an URL to make a webservice call to one of the service. I was successfully executed with the GET request but I am trying to execute this with the POST request but I am not getting any response. I was unable to get the content from the entity.
My URL: "https://maps.googleapis.com/maps/api/place/details/xml?reference=CoQBcQAAAEZ7yCju-0lhU7sZIBBe_On9jYImWzZ9Zt5rIg1tX6zaH02dHrQMHF1LFHY1_yUuXzsUf6m6-rrQJ8Ec_mGxBYtV85Wyb4anakaUi3QuZj7ygJXB3Fd5x69k_4UnDKMmEBNa410vbCXgQOGIkHCbNpcbC8ENxmVlUrqiifmdfuLgEhCtPATMhFRdsjuyAL_j__OEGhTnqujRRMYy_5-kxzcqCdMY4_1dbA&sensor=true&key=key1";
This was executed with the GET method. Below u can see my code.
public class HttpClientPostExample {
public static void main(String[] args) throws ClientProtocolException,
IOException {
String url = "https://maps.googleapis.com/maps/api/place/details/xml?";
HttpClient client = HttpClientBuilder.create().build();
// HttpRequest httpRequest = HttpsClientImpl.createRequest("Post", url);
HttpPost httpPost = new HttpPost(url);
List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>();
nameValuePairList
.add(new BasicNameValuePair(
"reference",
"CoQBcQAAAEZ7yCju-0lhU7sZIBBe_On9jYImWzZ9Zt5rIg1tX6zaH02dHrQMHF1LFHY1_yUuXzsUf6m6-rrQJ8Ec_mGxBYtV85Wyb4anakaUi3QuZj7ygJXB3Fd5x69k_4UnDKMmEBNa410vbCXgQOGIkHCbNpcbC8ENxmVlUrqiifmdfuLgEhCtPATMhFRdsjuyAL_j__OEGhTnqujRRMYy_5-kxzcqCdMY4_1dbA"));
nameValuePairList.add(new BasicNameValuePair("sensor", "true"));
nameValuePairList.add(new BasicNameValuePair("key",
"AIzaSyBA0Hu3is9qIJ5v6NEuofigk0y-aQwqiP0"));
httpPost.addHeader("User-Agent", "User-Agent");
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairList, "UTF-8"));
HttpResponse response = client.execute(httpPost);
System.out.println(response.getStatusLine().getStatusCode());
Header[] headerArray = response.getAllHeaders();
for (Header header : headerArray) {
System.out.println("Header Name: " + header.getName()
+ " Header Value: " + header.getValue());
}
}
Can any one help me on this. Is this the right approach to make a POST request...???
How can I get actual URL before firing/calling the execute method...???

Try to change your client instantiation technique from
HttpClient client = HttpClientBuilder.create().build();
to
DefaultHttpClient client = new DefaultHttpClient();
and to make sure that your entity has been fully consumed, make a call to EntityUtils.consume(entity) before showing the reponse headers:
...
HttpResponse response = client.execute(httpPost);
EntityUtils.consume(response.getEntity());
Header[] headerArray = response.getAllHeaders();
for (Header header : headerArray) {
System.out.println("Header Name: " + header.getName()
+ " Header Value: " + header.getValue());
}

Related

Microsoft graph API getMemberGroups returns 400 bad request. What could be the reason?

What could be the reason for a 400 (Bad request response) when using getMemberGroups API?
This is Java the code I'm using:
HttpClient client = HttpClientBuilder.create().build();
HttpPost request = new HttpPost(url);
request.addHeader("Content-Type", "application/json");
request.addHeader("Authorization", "Bearer " + accessToken);
List<NameValuePair> urlParameters = new ArrayList<>();
urlParameters.add(new BasicNameValuePair("securityEnabledOnly", "true"));
request.setEntity(new UrlEncodedFormEntity(urlParameters));
HttpResponse response;
final StatusLine statusLine;
try {
response = client.execute(request);
statusLine = response.getStatusLine();
} catch (IOException e) {
OutputUtil.printStacktrace(e);
return null;
}
Where url is "https://graph.microsoft.com/v1.0/me/getMemberGroups"
Another API call to "GET: memberOf" API does work. (with HttpGet object)
Try this :
String accessToken = "";
HttpClient client = HttpClientBuilder.create().build();
HttpPost request = new HttpPost("https://graph.microsoft.com/v1.0/me/getMemberGroups");
request.addHeader("Content-Type", "application/json");
request.addHeader("Authorization", "Bearer " + accessToken);
StringEntity requestEntity = new StringEntity("{\"securityEnabledOnly\": true}");
request.setEntity(requestEntity);
HttpResponse response;
final StatusLine statusLine;
response = client.execute(request);
statusLine = response.getStatusLine();
System.out.println(statusLine);
System.out.println(new String(response.getEntity().getContent().readAllBytes()));
Result:

Sending Bearer Token with HttpPost in Android

I couldn't find a way to authenticate my app with my server using the Bearer token I had created. it works perfectly with Postman though.
I've tried using UTF-8 encoding, using ?access_token in url, tried a lot of answers I found on Stackoverflow.
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("https://dmyzda2o.ui.nabu.casa/api/services/script/turn_on");
//httpPost.addHeader("Accept-Language", "he");
List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>();
nameValuePair.add(new BasicNameValuePair("Authorization", "Bearer eyJ0NiJ9.eyJpc3MiOiJmOWVkZDI5YjY2MTE0Mjc3YNDdmMzIwMWI2ZCIsImlhdCI6MTU1OTIwMjYwOCwiZXhwIjoxODc0NTYyNjA4fQ.HEb3b6kpW6OzAxcLumS8DlJWmZVAWfn0Lg84seBZGpQ"));
nameValuePair.add(new BasicNameValuePair("Content-Type", "application/json"));
nameValuePair.add(new BasicNameValuePair("entity_id", "script.gt11"));
Log.v("nameValue","entered");
try {
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair, HTTP.UTF_8));
The error I get is 401 Unauthorized on every attempt.
I'm using Volley, but when I set up the headers, I do it with this:
HashMap<String, String> headers = new HashMap<String, String>();
String authValue = "Bearer " + apiToken;
headers.put("Authorization", authValue);
headers.put("Accept", "application/json; charset=UTF-8");
headers.put("Content-Type", "application/json; charset=UTF-8");
The "Authorization" should not be a parameter. Its a header.
HttpPost request = new HttpPost(URL_SECURED_BY_BASIC_AUTHENTICATION);
String auth = DEFAULT_USER + ":" + DEFAULT_PASS;
byte[] encodedAuth = Base64.encodeBase64(
auth.getBytes(StandardCharsets.ISO_8859_1));
String authHeader = "Basic " + new String(encodedAuth);
request.setHeader(HttpHeaders.AUTHORIZATION, authHeader);
HttpClient client = HttpClientBuilder.create().build();
HttpResponse response = client.execute(request);
Why don't you use OK Http for networking requests? Then you can do something like this:
val request = Request.Builder()
.url(yourUrl)
.header("Authorization", "Bearer $yourToken")
.post(yourBody)
.build()

HttpUrlConnection POST not working as expected [duplicate]

lets assume this URL...
http://www.example.com/page.php?id=10
(Here id needs to be sent in a POST request)
I want to send the id = 10 to the server's page.php, which accepts it in a POST method.
How can i do this from within Java?
I tried this :
URL aaa = new URL("http://www.example.com/page.php");
URLConnection ccc = aaa.openConnection();
But I still can't figure out how to send it via POST
Updated answer
Since some of the classes, in the original answer, are deprecated in the newer version of Apache HTTP Components, I'm posting this update.
By the way, you can access the full documentation for more examples here.
HttpClient httpclient = HttpClients.createDefault();
HttpPost httppost = new HttpPost("http://www.a-domain.example/foo/");
// Request parameters and other properties.
List<NameValuePair> params = new ArrayList<NameValuePair>(2);
params.add(new BasicNameValuePair("param-1", "12345"));
params.add(new BasicNameValuePair("param-2", "Hello!"));
httppost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
//Execute and get the response.
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
if (entity != null) {
try (InputStream instream = entity.getContent()) {
// do something useful
}
}
Original answer
I recommend to use Apache HttpClient. its faster and easier to implement.
HttpPost post = new HttpPost("http://jakarata.apache.org/");
NameValuePair[] data = {
new NameValuePair("user", "joe"),
new NameValuePair("password", "bloggs")
};
post.setRequestBody(data);
// execute method and handle any error responses.
...
InputStream in = post.getResponseBodyAsStream();
// handle response.
for more information check this URL: http://hc.apache.org/
Sending a POST request is easy in vanilla Java. Starting with a URL, we need t convert it to a URLConnection using url.openConnection();. After that, we need to cast it to a HttpURLConnection, so we can access its setRequestMethod() method to set our method. We finally say that we are going to send data over the connection.
URL url = new URL("https://www.example.com/login");
URLConnection con = url.openConnection();
HttpURLConnection http = (HttpURLConnection)con;
http.setRequestMethod("POST"); // PUT is another valid option
http.setDoOutput(true);
We then need to state what we are going to send:
Sending a simple form
A normal POST coming from a http form has a well defined format. We need to convert our input to this format:
Map<String,String> arguments = new HashMap<>();
arguments.put("username", "root");
arguments.put("password", "sjh76HSn!"); // This is a fake password obviously
StringJoiner sj = new StringJoiner("&");
for(Map.Entry<String,String> entry : arguments.entrySet())
sj.add(URLEncoder.encode(entry.getKey(), "UTF-8") + "="
+ URLEncoder.encode(entry.getValue(), "UTF-8"));
byte[] out = sj.toString().getBytes(StandardCharsets.UTF_8);
int length = out.length;
We can then attach our form contents to the http request with proper headers and send it.
http.setFixedLengthStreamingMode(length);
http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
http.connect();
try(OutputStream os = http.getOutputStream()) {
os.write(out);
}
// Do something with http.getInputStream()
Sending JSON
We can also send json using java, this is also easy:
byte[] out = "{\"username\":\"root\",\"password\":\"password\"}" .getBytes(StandardCharsets.UTF_8);
int length = out.length;
http.setFixedLengthStreamingMode(length);
http.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
http.connect();
try(OutputStream os = http.getOutputStream()) {
os.write(out);
}
// Do something with http.getInputStream()
Remember that different servers accept different content-types for json, see this question.
Sending files with java post
Sending files can be considered more challenging to handle as the format is more complex. We are also going to add support for sending the files as a string, since we don't want to buffer the file fully into the memory.
For this, we define some helper methods:
private void sendFile(OutputStream out, String name, InputStream in, String fileName) {
String o = "Content-Disposition: form-data; name=\"" + URLEncoder.encode(name,"UTF-8")
+ "\"; filename=\"" + URLEncoder.encode(filename,"UTF-8") + "\"\r\n\r\n";
out.write(o.getBytes(StandardCharsets.UTF_8));
byte[] buffer = new byte[2048];
for (int n = 0; n >= 0; n = in.read(buffer))
out.write(buffer, 0, n);
out.write("\r\n".getBytes(StandardCharsets.UTF_8));
}
private void sendField(OutputStream out, String name, String field) {
String o = "Content-Disposition: form-data; name=\""
+ URLEncoder.encode(name,"UTF-8") + "\"\r\n\r\n";
out.write(o.getBytes(StandardCharsets.UTF_8));
out.write(URLEncoder.encode(field,"UTF-8").getBytes(StandardCharsets.UTF_8));
out.write("\r\n".getBytes(StandardCharsets.UTF_8));
}
We can then use these methods to create a multipart post request as follows:
String boundary = UUID.randomUUID().toString();
byte[] boundaryBytes =
("--" + boundary + "\r\n").getBytes(StandardCharsets.UTF_8);
byte[] finishBoundaryBytes =
("--" + boundary + "--").getBytes(StandardCharsets.UTF_8);
http.setRequestProperty("Content-Type",
"multipart/form-data; charset=UTF-8; boundary=" + boundary);
// Enable streaming mode with default settings
http.setChunkedStreamingMode(0);
// Send our fields:
try(OutputStream out = http.getOutputStream()) {
// Send our header (thx Algoman)
out.write(boundaryBytes);
// Send our first field
sendField(out, "username", "root");
// Send a seperator
out.write(boundaryBytes);
// Send our second field
sendField(out, "password", "toor");
// Send another seperator
out.write(boundaryBytes);
// Send our file
try(InputStream file = new FileInputStream("test.txt")) {
sendFile(out, "identification", file, "text.txt");
}
// Finish the request
out.write(finishBoundaryBytes);
}
// Do something with http.getInputStream()
String rawData = "id=10";
String type = "application/x-www-form-urlencoded";
String encodedData = URLEncoder.encode( rawData, "UTF-8" );
URL u = new URL("http://www.example.com/page.php");
HttpURLConnection conn = (HttpURLConnection) u.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty( "Content-Type", type );
conn.setRequestProperty( "Content-Length", String.valueOf(encodedData.length()));
OutputStream os = conn.getOutputStream();
os.write(encodedData.getBytes());
The first answer was great, but I had to add try/catch to avoid Java compiler errors.
Also, I had troubles to figure how to read the HttpResponse with Java libraries.
Here is the more complete code :
/*
* Create the POST request
*/
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://example.com/");
// Request parameters and other properties.
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("user", "Bob"));
try {
httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
} catch (UnsupportedEncodingException e) {
// writing error to Log
e.printStackTrace();
}
/*
* Execute the HTTP Request
*/
try {
HttpResponse response = httpClient.execute(httpPost);
HttpEntity respEntity = response.getEntity();
if (respEntity != null) {
// EntityUtils to get the response content
String content = EntityUtils.toString(respEntity);
}
} catch (ClientProtocolException e) {
// writing exception to log
e.printStackTrace();
} catch (IOException e) {
// writing exception to log
e.printStackTrace();
}
A simple way using Apache HTTP Components is
Request.Post("http://www.example.com/page.php")
.bodyForm(Form.form().add("id", "10").build())
.execute()
.returnContent();
Take a look at the Fluent API
I suggest using Postman to generate the request code. Simply make the request using Postman then hit the code tab:
Then you'll get the following window to choose in which language you want your request code to be:
simplest way to send parameters with the post request:
String postURL = "http://www.example.com/page.php";
HttpPost post = new HttpPost(postURL);
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("id", "10"));
UrlEncodedFormEntity ent = new UrlEncodedFormEntity(params, "UTF-8");
post.setEntity(ent);
HttpClient client = new DefaultHttpClient();
HttpResponse responsePOST = client.execute(post);
You have done. now you can use responsePOST.
Get response content as string:
BufferedReader reader = new BufferedReader(new InputStreamReader(responsePOST.getEntity().getContent()), 2048);
if (responsePOST != null) {
StringBuilder sb = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
System.out.println(" line : " + line);
sb.append(line);
}
String getResponseString = "";
getResponseString = sb.toString();
//use server output getResponseString as string value.
}
Using okhttp :
Source code for okhttp can be found here https://github.com/square/okhttp.
If you're writing a pom project, add this dependency
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>4.2.2</version>
</dependency>
If not simply search the internet for 'download okhttp'. Several results will appear where you can download a jar.
your code :
import okhttp3.*;
import java.io.IOException;
public class ClassName{
private void sendPost() throws IOException {
// form parameters
RequestBody formBody = new FormBody.Builder()
.add("id", 10)
.build();
Request request = new Request.Builder()
.url("http://www.example.com/page.php")
.post(formBody)
.build();
OkHttpClient httpClient = new OkHttpClient();
try (Response response = httpClient.newCall(request).execute()) {
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
// Get response body
System.out.println(response.body().string());
}
}
}
Easy with java.net:
public void post(String uri, String data) throws Exception {
HttpClient client = HttpClient.newBuilder().build();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(uri))
.POST(BodyPublishers.ofString(data))
.build();
HttpResponse<?> response = client.send(request, BodyHandlers.discarding());
System.out.println(response.statusCode());
Here is more information:
https://openjdk.java.net/groups/net/httpclient/recipes.html#post
Since java 11, HTTP requests can be made by using java.net.http.HttpClient with less code.
var values = new HashMap<String, Integer>() {{
put("id", 10);
}};
var objectMapper = new ObjectMapper();
String requestBody = objectMapper
.writeValueAsString(values);
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("http://www.example.com/abc"))
.POST(HttpRequest.BodyPublishers.ofString(requestBody))
.build();
HttpResponse<String> response = client.send(request,
HttpResponse.BodyHandlers.ofString());
System.out.println(response.body());
Call HttpURLConnection.setRequestMethod("POST") and HttpURLConnection.setDoOutput(true); Actually only the latter is needed as POST then becomes the default method.
I recomend use http-request built on apache http api.
HttpRequest<String> httpRequest = HttpRequestBuilder.createPost("http://www.example.com/page.php", String.class)
.responseDeserializer(ResponseDeserializer.ignorableDeserializer()).build();
public void send(){
String response = httpRequest.execute("id", "10").get();
}

HTTPClient "main" java.lang.NoSuchFieldError: INSTANCE at org.apache.http.conn.ssl.SSLConnectionSocketFactory.<clinit>

I'm using Httpclient-4.5.2.jar and httpcore-4.4.4.jar HttpClient components and I'm getting below error.
Exception in thread "main" java.lang.NoSuchFieldError: INSTANCE
at org.apache.http.conn.ssl.SSLConnectionSocketFactory.<clinit>(SSLConnectionSocketFactory.java:144)
at org.apache.http.impl.client.HttpClientBuilder.build(HttpClientBuilder.java:966)
My source code as follows.
try {
System.out.println("came to try catch");
HttpClient httpClient = HttpClientBuilder.create().build();
HttpPost request = new HttpPost("https://bizz.mobilezz.lk/apicall/loanprepaidapi/v1");
StringEntity params =new StringEntity("{\"mobile\":\"776037285\",\"path\":\"IVV\",\"loanAmount\":\"200000\"}");
request.addHeader("content-type", "application/json");
request.addHeader("Authorization", "Bearer casmk34233mlacscmaacsac");
request.addHeader("Accept", "application/json");
request.setEntity(params);
HttpResponse response = httpClient.execute(request);
System.out.println("response is :"+response.getStatusLine());
} catch (Exception e) {
e.printStackTrace();
Please assist me to get rid of this error. I'm trying to send request in post method and get json response.
I found an answer to my question and posting for your reference.
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(
"https://bizz.mobilezz.lk/apicall/loanprepaidapi/v1");
JSONObject json = new JSONObject();
StringEntity params = new StringEntity("{\"msisdn\":\"" + mobile
+ "\",\"channel\":\"SDD\"}");
new StringEntity(json.toString());
post.addHeader("Host", "mife.dialog.lk");
post.addHeader("content-type", "application/json");
post.addHeader("Authorization", "Bearer " + access_token);
post.addHeader("Accept", "application/json");
// System.out.println("status code is:" + status);
post.setEntity(params);
HttpResponse response = client.execute(post);
int status = response.getStatusLine().getStatusCode();
System.out.println("status code is :" + status);
resCode = Integer.toString(status);
if (status != 401) {
if (status != 409) {
BufferedReader rd = new BufferedReader(
new InputStreamReader(response.getEntity()
.getContent()));
String response1 = readAll(rd);
System.out.println(response1);
JSONObject obj = new JSONObject(response1);
resCode = obj.getString("resCode");
resDesc = obj.getString("resDesc");
System.out.println(resCode);
System.out.println(resDesc);
}
}
System.out.println("reason code is :" + resCode);

Send xml message over HTTP POST

I require to send an HL7 message, which is parsed into an XML message to the below end point.
Host: iol.sandbox.ohie.org
Port: 5001
username: admin
password: admin
HTTP method: POST
HTTP Path: /ws/rest/v1/patients/
I am using Apache HttpClient to achieve this. Below is the code which I am using.
public void simpleHttpMessage() throws Exception{
String url = "iol.sandbox.ohie.org";
String USER_AGENT = "/ws/rest/v1/patients/";
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
// add header
post.setHeader("User-Agent", USER_AGENT);
List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
urlParameters.add(new BasicNameValuePair("username", "admin"));
urlParameters.add(new BasicNameValuePair("password", "admin"));
post.setEntity(new UrlEncodedFormEntity(urlParameters));
HttpResponse response = client.execute(post);
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Post parameters : " + post.getEntity());
System.out.println("Response Code : " +
response.getStatusLine().getStatusCode());
BufferedReader rd = new BufferedReader(
new InputStreamReader(response.getEntity().getContent()));
StringBuffer result = new StringBuffer();
String line = "";
while ((line = rd.readLine()) != null) {
result.append(line);
}
System.out.println(result.toString());
}
I am not sure where I should pass the actual xml message which I want to send. I am basically trying to send a HL7 message which is parsed into XML, over HTTP POST.
I would be grateful if someone who help me with what I am missing from the above code snippet.
So if you are trying to put the xml into the body
String xml = "<xml>xxxx</xml>";
HttpEntity entity = new ByteArrayEntity(xml.getBytes("UTF-8"));
post.setEntity(entity);
I believe that should work. But I really only deal with C#. Where is the xml?

Categories

Resources