Curl Equivalent in Java

cURL equivalent in JAVA

Exception handling omitted:

HttpURLConnection con = (HttpURLConnection) new URL("https://www.example.com").openConnection();
con.setRequestMethod("POST");
con.getOutputStream().write("LOGIN".getBytes("UTF-8"));
con.getInputStream();

What will be the equivalent to following curl command in java

Http(s)UrlConnection may be your weapon of choice:

public String sendData() throws IOException {
// curl_init and url
URL url = new URL("http://some.host.com/somewhere/to/");
HttpURLConnection con = (HttpURLConnection) url.openConnection();

// CURLOPT_POST
con.setRequestMethod("POST");

// CURLOPT_FOLLOWLOCATION
con.setInstanceFollowRedirects(true);

String postData = "my_data_for_posting";
con.setRequestProperty("Content-length", String.valueOf(postData.length()));

con.setDoOutput(true);
con.setDoInput(true);

DataOutputStream output = new DataOutputStream(con.getOutputStream());
output.writeBytes(postData);
output.close();

// "Post data send ... waiting for reply");
int code = con.getResponseCode(); // 200 = HTTP_OK
System.out.println("Response (Code):" + code);
System.out.println("Response (Message):" + con.getResponseMessage());

// read the response
DataInputStream input = new DataInputStream(con.getInputStream());
int c;
StringBuilder resultBuf = new StringBuilder();
while ( (c = input.read()) != -1) {
resultBuf.append((char) c);
}
input.close();

return resultBuf.toString();
}

I'm not quite sure about the HTTPS_VERIFYPEER-thing, but this may give you a starting point.

Equivalent of curl command in java

With HttpClient of apache you can do it:

...
import org.apache.http.client.methods.HttpPost;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity
import org.apache.http.Consts;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.HttpEntity;
....

public String sendPost(String url, Map<String, String> postParams,
Map<String, String> header, String cookies) {

HttpPost httpPost = new HttpPost(url);
List<NameValuePair> formParams = new ArrayList<NameValuePair>();
HttpClientBuilder clientBuilder = HttpClients.createDefault();
CloseableHttpClient httpclient = clientBuilder.build();

if (header != null) {
Iterator<Entry<String, String>> itCabecera = header.entrySet().iterator();
while (itCabecera.hasNext()) {
Entry<String, String> entry = itCabecera.next();

httpPost.addHeader(entry.getKey(), entry.getValue());
}
}

httpPost.setHeader("Cookie", cookies);

if (postParams != null) {
Iterator<Entry<String, String>> itParms = postParams.entrySet().iterator();
while (itParms.hasNext()) {
Entry<String, String> entry = itParms.next();

formParams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
}

UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(formParams, Consts.UTF_8);
httpPost.setEntity(formEntity);

CloseableHttpResponse httpResponse = httpclient.execute(httpPost);

HttpEntity entity = httpResponse.getEntity();
if (entity != null) {
pageContent = EntityUtils.toString(entity);
}

return pageContent;
}

I hope this help you.

EDIT:

I add the way to send a file. I put in a code separate to not mix code (it is an approximation, based on this examples):

File file = new File("path/to/file");
String message = "This is a multipart post";
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);

if (postParams != null) {
Iterator<Entry<String, String>> itParms = postParams.entrySet().iterator();
while (itParms.hasNext()) {
Entry<String, String> entry = itParms.next();

builder.addTextBody(entry.getKey(), entry.getValue(), ContentType.DEFAULT_BINARY);
}
}

builder.addTextBody("text", message, ContentType.DEFAULT_BINARY);

HttpEntity entity = builder.build();
httpPost.setEntity(entity);

Java equivalent of a curl cookie statement

I would advise a different approach. Instead of coding the HTTP request on your own, I would suggest using a third party library that does it for you. Well known libraries are Apache HTTP Client and OK Http Client. However, there is by far less known but much simpler Http Client in Open Source MgntUtils library (written by me). Your code may look something like this

HttpClient client = new HttpClient();
client.setContentType("application/json; charset=utf-8");
client.setConnectionUrl("http://egurl/app/app1/session/login");
client.sendHttpRequest(HttpMethod.POST, "{\"username\":\"acd\",\"password\":\"pwd\",\"isPasswordEncrypted\":\"false\"}");

Here is the link to JavaDoc for the HttpClient. The MgntUtils library could be found as Maven artifact and at Github (with source code and Javadoc)

BTW, it appears that in your curl you don't set Request property "Cookie" but just send your String {\"username\":\"acd\",\"password\":\"pwd\",\"isPasswordEncrypted\":\"false\"}" to the server as body of your request. That is what my sample code does. If you need to set a request property there is a method for this as well

public void setRequestProperty(java.lang.String propertyName,
java.lang.String value)


Related Topics



Leave a reply



Submit