Sending Http Post Request in Java

Java - sending HTTP parameters via POST method easily

In a GET request, the parameters are sent as part of the URL.

In a POST request, the parameters are sent as a body of the request, after the headers.

To do a POST with HttpURLConnection, you need to write the parameters to the connection after you have opened the connection.

This code should get you started:

String urlParameters  = "param1=a¶m2=b¶m3=c";
byte[] postData = urlParameters.getBytes( StandardCharsets.UTF_8 );
int postDataLength = postData.length;
String request = "http://example.com/index.php";
URL url = new URL( request );
HttpURLConnection conn= (HttpURLConnection) url.openConnection();
conn.setDoOutput( true );
conn.setInstanceFollowRedirects( false );
conn.setRequestMethod( "POST" );
conn.setRequestProperty( "Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty( "charset", "utf-8");
conn.setRequestProperty( "Content-Length", Integer.toString( postDataLength ));
conn.setUseCaches( false );
try( DataOutputStream wr = new DataOutputStream( conn.getOutputStream())) {
wr.write( postData );
}

Java doesn't send HTTP POST Request

I tested this and it's working:

//Sender.java
String url = "http://localhost:8082/";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();


con.setRequestMethod("POST");
con.setDoOutput(true);

OutputStream os = con.getOutputStream();
os.write("Just Some Text".getBytes("UTF-8"));
os.flush();

int httpResult = con.getResponseCode();
con.disconnect();

As you can see, connect is not necessary. The key line is

int httpResult = con.getResponseCode();

sending HTTP POST requests in Java

So I did some research and found this!

package com.*********.xyz;

import java.io.IOException;
import java.util.Scanner;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

public class Main {
public static void main(String[] args) throws IOException, InterruptedException {
String body = "this is the message you are going to post!";

HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("http://192.168.1.46:4046/authenticate"))
.headers("Content-Type", "text/plain;charset=UTF-8")
.POST(HttpRequest.BodyPublishers.ofString(body))
.build();
HttpResponse<String> response = client.send(request,
HttpResponse.BodyHandlers.ofString());

System.out.println(response);
//Should print 200 after sending the response if the server is active
}
}

This code works without any third-party libraries.

Java 11 sending HTTP post request without body

You should be able to do the same with HttpClient - on Jdk 11 if I enable logging with -Djdk.httpclient.HttpClient.log=requests,headers I can see that Content-Length: 0 is sent with the following request:

HttpRequest request = HttpRequest.newBuilder()
.uri(<uri>)
.header("Authorization", "Bearer " + <token>)
.version(HttpClient.Version.HTTP_1_1)
.POST(HttpRequest.BodyPublishers.noBody())
.build();
HttpResponse<String> httpResponse = httpClient.send(request, HttpResponse.BodyHandlers.ofString());

How to send post request in java with a JSON body

This Question is asked before here:
HTTP POST using JSON in Java

See it and comment this if you face any problem.

How to send simple http post request with post parameters in java

HTTP POST request example using Apache HttpClient v.4.x

HttpClient httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(url);
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.addTextBody("param1", param1Value, ContentType.TEXT_PLAIN);
builder.addTextBody("param2", param2Value, ContentType.TEXT_PLAIN);
HttpEntity multipart = builder.build();
httpPost.setEntity(multipart);
HttpResponse response = httpClient.execute(httpMethod);

Http Post Request

yes json is easy. i implemented this and its working fine.. thanks to JLONG and user1369434.

package m.example.postrwq;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONObject;

import android.support.v7.app.ActionBarActivity;
import android.app.Activity;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends ActionBarActivity {
Button btnPost;
TextView tvIsConnected;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

btnPost = (Button) findViewById(R.id.button1);
tvIsConnected = (TextView) findViewById(R.id.textView1);

if(isConnected()){
tvIsConnected.setBackgroundColor(0xFF00CC00);
tvIsConnected.setText("You are conncted");
}
else{
tvIsConnected.setText("You are NOT conncted");
}
btnPost.setOnClickListener(new OnClickListener(){

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
new HttpAsyncTask().execute("http://hmkcode.appspot.com/jsonservlet");
}});


}
private class HttpAsyncTask extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... urls) {



return POST(urls[0]);
}
// onPostExecute displays the results of the AsyncTask.
@Override
protected void onPostExecute(String result) {
Toast.makeText(getBaseContext(), "Data Sent!", Toast.LENGTH_LONG).show();
}
}
public static String POST(String url){
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 = "my string";




// 6. set json to StringEntity
StringEntity se = new StringEntity(json);

// 7. set httpPost Entity
httpPost.setEntity(se);

// 8. Set some headers to inform server about the type of the content
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");

// 9. Execute POST request to the given URL
HttpResponse httpResponse = httpclient.execute(httpPost);

// 10. receive response as inputStream
inputStream = httpResponse.getEntity().getContent();

// 11. convert inputstream to string
if(inputStream != null)
result = convertInputStreamToString(inputStream);
else
result = "Did not work!";

} catch (Exception e) {
Log.d("InputStream", e.getLocalizedMessage());
}
// 12. return result
return result;

}

private static String convertInputStreamToString(InputStream inputStream) throws IOException {
// TODO Auto-generated method stub

BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream));
String line = "";
String result = "";
while((line = bufferedReader.readLine()) != null)
result += line;

inputStream.close();
return result;

}
public boolean isConnected() {
// TODO Auto-generated method stub
ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Activity.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected())
return true;
else
return false;
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {

// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}


}

hope this will help others



Related Topics



Leave a reply



Submit