[英]Equivalent of curl command in java
我想要一些幫助在Java中編寫等效於下面的curl命令的內容。
curl -X POST --header 'Content-Type: application/json' --header 'Accept: application/json' --header 'cookie: [APP COOKIES];' -d 'sampleFile.json' 'https://url.com'
您嘗試使用RESTful Web服務,因此應使用jax-rs或spring REST之類的庫,這是使用RESTful Web服務的示例,您可以找到許多具有更多詳細信息的示例。
我認為您正在尋找的答案是哪個庫提供Java創建HTTP請求。 什么是用於HTTP POST,GET等的最佳Java庫? 該問題為您提供了所需的所有答案
使用apache的HttpClient可以做到:
...
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;
}
希望對您有所幫助。
編輯:
我添加了發送文件的方式。 我單獨輸入了一個代碼,以免混淆代碼(根據此示例 ,這是一個近似值):
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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.