Send the requestbody of one API to another API - java

Here is my code
private static final String MEDIA_TYPE = "application/json";
private static final String FORMAT = "UTF-8";
private static String baseServiceUrl;
private static String apiServiceUrl;
#RequestMapping("/")
public ResponseEntity<?> getMessage() throws Exception {
logger.info("Started");
try {
messageProcessor.getMessage("test service");
// Read from request
StringBuilder buffer = new StringBuilder();
BufferedReader reader = request.getReader();
String line;
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String data = buffer.toString();
StringRequestEntity requestEntity = null;
HttpClient httpclient = new HttpClient();
int statusCode;
logger.info("RequestBody"+data);
baseServiceUrl="http://localhost:8080/services";
apiServiceUrl="/services/rest/json";
StringBuffer eventResponse = new StringBuffer();
requestEntity = new StringRequestEntity(data, MEDIA_TYPE, FORMAT);
PostMethod postMethod = new PostMethod(baseServiceUrl+apiServiceUrl);
postMethod.setRequestEntity(requestEntity);
statusCode = httpclient.executeMethod(postMethod);
logger.info("Status code"+statusCode);
}
catch (Exception ex) {
logger.error("Exception occurs ", ex);
return new ResponseEntity("Internal server error !!", HttpStatus.INTERNAL_SERVER_ERROR);
}
return new ResponseEntity("Successfully called the service!!", HttpStatus.OK);
}
I want to get the requestbody of one API and send to another API .And a json is my request body.But in this code,I got the status code as 400.Can anyone help me to solve the problem

I think you have appended the /services in the url twice. It should be like:
baseServiceUrl="http://localhost:8080/services";
apiServiceUrl="/rest/json";

In your code you are reading the request body as a string , could you share the request body that is logged.The HTTP response code 400 corresponds to BAD request . So probably, either the endpoint that you are trying to hit is different or the request body has an issue. Try removing the /services from your apiServiceUrl to correct the url path.Also, since you are most probably having a json as request body try the following approach :
String json = "{"id":1,"name":"xxxx"}";
StringEntity entity = new StringEntity(json);
postMethod.setEntity(entity);
postMethod.setHeader("Accept", "application/json");
postMethod.setHeader("Content-type", "application/json");
make sure that the string that you read from the request using BufferedReader reader = request.getReader(); is in appropriate json format.

Related

POST request with Multipart File and parameters in Java

I have POST API endpoint in Java , which is like below which is to be called for storing student marksheet in the portal.
POST API endpoint
/**
#param name
Name of student
#param class
Class of student
#param section
Section of student
#param rollno
Roll Number of student
#param file
Marksheet of student in .xlsx format
**/
#PostMapping(value="/storeMarksheet", produces = "application/json")
public String performTaskAndSendResponse(
#RequestParam String name,
#RequestParam String class,
#RequestParam String section,
#RequestParam String rollno,
#RequestPart(name=file) #ApiParam(".xlsx file") MultipartFile file
){
System.out.println("Inside store marksheet endpoint") // not getting printed
// Store marksheet and return response accordingly
}
And have written a function like below to call it
POST API function call
public String postAPI(String name, String class, String section, String rollno, MultipartFile marksheet){
Map<String, Object> student = new HashMap<String, Object>;
student.put("name", name);
student.put("class", class);
student.put("section", section);
student.put("rollno", rollno);
student.put("file", marksheet);
String dataAsString = student.toString();
String API = "https://somedomain.com/example/storeMarksheet";
StringBuilder resp = new StringBuilder();
String lineResponse = null;
try{
URL url = new URL(API);
HttpURLConnection conn = (HttpURLConnection) url.openConnection(); // Using HttpURL connection
conn.setRequestMethod("POST");
conn.setDoOutput(true);
DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
dos.write(dataAsString.getBytes("utf-8"));
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream(),"utf-8"));
while((lineResponse = br.readLine()) != null) resp.append(lineResponse.trim());
System.out.println(resp.toString());
return resp;
}catch(Exception e){
return null;
}
}
However seems like the call is not going at all.
Using HttpURLConnection for making http calls.
NOTE
First priority is sending via HttpURLConnection only, if impossible
then open to other solutions
The above POST API endpoint is working perfectly in swagger.
Tried to do via HttpURLConnection but nothing worked for me. Therefore posting answer using another process
public String postAPI(String name, String class, String section, String rollno, MultipartFile marksheet){
String responseStr = null;
try{
HttpPost req = new HttpPost("https://somedomain.com/example/storeMarksheet");
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
builder.addTextBody("name",name);
builder.addTextBody("class",class);
builder.addTextBody("section",section);
builder.addTextBody("rollno",rollno);
builder.addbinaryBody("file", marksheet.getBytes(), ContentType.DEFAULT_BINARY, marksheet.getOriginalFilename() );
HttpEntity entity = builder.build();
req.setEntity(entity);
CloseableHttpClient client = HttpClientBuilder.create().build();
CloseableHttpResponse res = client.execute(req);
responseStr = EntityUtils.toString(res.getEnity().toString());
System.out.println(responseStr);
return responseStr;
}catch(Exception e){
//do something.. have put common exception for now
return null;
}finally{
try{
res.close();
client.close();
}catch(Exception e){
//do something.. have put common exception for now
}
}
}

Should I use HttpURLConnection or RestTemplate [duplicate]

This question already has an answer here:
RestTemplate vs Apache Http Client for production code in spring project
(1 answer)
Closed 4 years ago.
Should I use HttpURLConnection in a Spring Project Or better to use RestTemplate ?
In other words, When it is better to use each ?
The HttpURLConnection and RestTemplate are different kind of beasts. They operate on different abstraction levels.
The RestTemplate helps to consume REST api and the HttpURLConnection works with HTTP protocol.
You're asking what is better to use. The answer depends on what you're trying to achieve:
If you need to consume REST api then stick with RestTemplate
If you need to work with http protocol then use HttpURLConnection, OkHttpClient, Apache's HttpClient, or if you're using Java 11 you can try its HttpClient.
Moreover the RestTemplate uses HttpUrlConnection/OkHttpClient/... to do its work (see ClientHttpRequestFactory, SimpleClientHttpRequestFactory, OkHttp3ClientHttpRequestFactory
Why you should not use HttpURLConnection?
It's better to show some code:
In examples below JSONPlaceholder used
Let's GET a post:
public static void main(String[] args) {
URL url;
try {
url = new URL("https://jsonplaceholder.typicode.com/posts/1");
} catch (MalformedURLException e) {
// Deal with it.
throw new RuntimeException(e);
}
HttpURLConnection connection = null;
try {
connection = (HttpURLConnection) url.openConnection();
try (InputStream inputStream = connection.getInputStream();
InputStreamReader isr = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(isr)) {
// Wrap, wrap, wrap
StringBuilder response = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
response.append(line);
}
// Here is the response body
System.out.println(response.toString());
}
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
if (connection != null) {
connection.disconnect();
}
}
}
Now let's POST a post something:
connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-type", "application/json; charset=UTF-8");
try (OutputStream os = connection.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter wr = new BufferedWriter(osw)) {
wr.write("{\"title\":\"foo\", \"body\": \"bar\", \"userId\": 1}");
}
If the response needed:
try (InputStream inputStream = connection.getInputStream();
InputStreamReader isr = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(isr)) {
// Wrap, wrap, wrap
StringBuilder response = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
response.append(line);
}
System.out.println(response.toString());
}
As you can see the api provided by the HttpURLConnection is ascetic.
You always have to deal with "low-level" InputStream, Reader, OutputStream, Writer, but fortunately there are alternatives.
The OkHttpClient
The OkHttpClient reduces the pain:
GETting a post:
OkHttpClient okHttpClient = new OkHttpClient();
Request request = new Request.Builder()
.url("https://jsonplaceholder.typicode.com/posts/1")
.build();
Call call = okHttpClient.newCall(request);
try (Response response = call.execute();
ResponseBody body = response.body()) {
String string = body.string();
System.out.println(string);
} catch (IOException e) {
throw new RuntimeException(e);
}
POSTing a post:
Request request = new Request.Builder()
.post(RequestBody.create(MediaType.parse("application/json; charset=UTF-8"),
"{\"title\":\"foo\", \"body\": \"bar\", \"userId\": 1}"))
.url("https://jsonplaceholder.typicode.com/posts")
.build();
Call call = okHttpClient.newCall(request);
try (Response response = call.execute();
ResponseBody body = response.body()) {
String string = body.string();
System.out.println(string);
} catch (IOException e) {
throw new RuntimeException(e);
}
Much easier, right?
Java 11's HttpClient
GETting the posts:
HttpClient httpClient = HttpClient.newHttpClient();
HttpResponse<String> response = httpClient.send(HttpRequest.newBuilder()
.uri(URI.create("https://jsonplaceholder.typicode.com/posts/1"))
.GET()
.build(), HttpResponse.BodyHandlers.ofString());
System.out.println(response.body());
POSTing a post:
HttpResponse<String> response = httpClient.send(HttpRequest.newBuilder()
.header("Content-Type", "application/json; charset=UTF-8")
.uri(URI.create("https://jsonplaceholder.typicode.com/posts"))
.POST(HttpRequest.BodyPublishers.ofString("{\"title\":\"foo\", \"body\": \"barzz\", \"userId\": 2}"))
.build(), HttpResponse.BodyHandlers.ofString());
The RestTemplate
According to its javadoc:
Synchronous client to perform HTTP requests, exposing a simple, template method API over underlying HTTP client libraries such as the JDK {#code HttpURLConnection}, Apache HttpComponents, and others.
Lets do the same
Firstly for convenience the Post class is created. (When the RestTemplate will read the response it will transform it to a Post using HttpMessageConverter)
public static class Post {
public long userId;
public long id;
public String title;
public String body;
#Override
public String toString() {
return new ReflectionToStringBuilder(this)
.toString();
}
}
GETting a post.
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<Post> entity = restTemplate.getForEntity("https://jsonplaceholder.typicode.com/posts/1", Post.class);
Post post = entity.getBody();
System.out.println(post);
POSTing a post:
public static class PostRequest {
public String body;
public String title;
public long userId;
}
public static class CreatedPost {
public String body;
public String title;
public long userId;
public long id;
#Override
public String toString() {
return new ReflectionToStringBuilder(this)
.toString();
}
}
public static void main(String[] args) {
PostRequest postRequest = new PostRequest();
postRequest.body = "bar";
postRequest.title = "foo";
postRequest.userId = 11;
RestTemplate restTemplate = new RestTemplate();
CreatedPost createdPost = restTemplate.postForObject("https://jsonplaceholder.typicode.com/posts/", postRequest, CreatedPost.class);
System.out.println(createdPost);
}
So to answer your question:
When it is better to use each ?
Need to consume REST api? Use RestTemplate
Need to work with http? Use some HttpClient.
Also worth mentioning:
Retrofit
Intro to Feign
Declarative REST client

how to call web service in java using post method

public static String[] Webcall(String emailID) {
try {
URL url = new URL(AppConfig.URL + emailID);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Accept", "application/json");
conn.setRequestProperty("Authorization", "application/json");
conn.setRequestProperty("userEmailId", emailID);
if (conn.getResponseCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
}
conn.disconnect();
org.json.JSONObject _jsonObject = new org.json.JSONObject(output);
org.json.JSONArray _jArray = _jsonObject.getJSONArray("manager");
String[] str = new String[_jArray.length()];
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
This is my code I am trying to call web service and get data.
But when I hit web service then I am getting below exception
Failed : HTTP error code : 404
Please suggest me where am doing wrong try to give solution for this .
The first thing is check url is it working on computer using postman or restclient and if it is working fine then tried to post using below code, this code is for posting data in json format using HttpPost you can use retrofit lib as Milad suggested.
public static String POST(String url, String email)
{
InputStream inputStream = null;
String result = "";
try {
// 1. create HttpClient
HttpClient httpclient = new DefaultHttpClient();
// 2. make POST request to the given URL
HttpPost httpPost = new HttpPost(url);
String json = "";
// 3. build jsonObject
JSONObject jsonObject = new JSONObject();
jsonObject.accumulate("email", email);
// 4. convert JSONObject to JSON to String
json = jsonObject.toString();
// 5. set json to StringEntity
StringEntity se = new StringEntity(json);
// 6. set httpPost Entity
httpPost.setEntity(se);
// 7. Set some headers to inform server about the type of the content
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
// 8. Execute POST request to the given URL
HttpResponse httpResponse = httpclient.execute(httpPost);
// 9. receive response as inputStream
inputStream = httpResponse.getEntity().getContent();
// 10. convert inputstream to string
if(inputStream != null)
result = convertInputStreamToString(inputStream);
else
result = "Did not work!";
} catch (Exception e) {
Log.d("InputStream", e.getLocalizedMessage());
}
// 11. return result
return result;
}
private static String convertInputStreamToString(InputStream inputStream) throws IOException{
BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream));
String line = "";
String result = "";
while((line = bufferedReader.readLine()) != null)
result += line;
inputStream.close();
return result;
}
I think u should try to re-check URL that you send request to.
follow the output error, code 404 that mean the URL is broken or dead link.
You can do the same by using jersy-client and jersy core.Here is the code snippet
private static void generateXML(String xmlName, String requestXML, String url)
{
try
{
Client client = Client.create();
WebResource webResource = client
.resource(url);
ClientResponse response = (ClientResponse)webResource.accept(new String[] { "application/xml" }).post(ClientResponse.class, requestXML);
if (response.getStatus() != 200) {
throw new RuntimeException("Failed : HTTP error code : " + response.getStatus());
}
String output = (String)response.getEntity(String.class);
PrintWriter writer = new PrintWriter(xmlName, "UTF-8");
writer.println(output);
writer.close();
}
catch (Exception e) {
try {
throw new CustomException("Rest-Client May Be Not Working From Your System");
} catch (CustomException e1) {
System.exit(1);
}
}
}
Call this method from your code with varibales.

Error with apache http client java program

I have got an issue with a simple program to get the data from an url using 'apache http client (4.5.2 version)'.
Please find the code and the error below:
public static void main(String[] args) throws Exception {
String username = "user";
String password = "pwd";
String urlString = "xyz.com?a=b&c=d";
org.apache.http.client.HttpClient client = HttpClientBuilder.create().build();
HttpGet request = new HttpGet(urlString);
org.apache.http.auth.UsernamePasswordCredentials creds = new org.apache.http.auth.UsernamePasswordCredentials(
username, password);
request.addHeader(new BasicScheme().authenticate(creds, request));
HttpResponse response = client.execute(request);
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) {
System.out.println(line);
result.append(line);
}
}
Error:
<Error><Code>InvalidArgument</Code><Message>Only one auth mechanism allowed; only the X-Amz-Algorithm query parameter, Signature query string parameter or the Authorization header should be specified</Message>
Could you please help ?
I did not experience the error above, but I was able to run this code sample with no error after adding "http://" to the beginning of the given
String urlString = "xyz.com?a=b&c=d";

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();
}

Categories

Resources