HttpClient发送json、普通参数类型的请求
1、Post请求传json数据
JSONObject json = new JSONObject();
json.put("filePath","js");
json.put("projectId","61020ccdfd33d86b6abe8745");
json.put("type","fileFolder");
httpPost.setEntity(new StringEntity(json.toString(),"UTF-8"));
2、Post请求传普通参数
JSONObject json = new JSONObject();
json.put("filePath","js");
json.put("projectId","61020ccdfd33d86b6abe8745");
json.put("type","fileFolder");
List<NameValuePair> parameters = new ArrayList<NameValuePair>();
for(String key:json.keySet()) {
parameters.add(new BasicNameValuePair(key, json.getString(key)));
}
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(parameters, "UTF-8");
httpPost.setEntity(formEntity);
maven依赖:
<dependency>
<groupId>commons-httpclient</groupId>
<artifactId>commons-httpclient</artifactId>
<version>3.1</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.76</version>
</dependency>
完整代码:
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class HttpClientUtil {
public static String url = "http://192.168.9.247:3080/co/cmd/deleteProject";
public static void deletePost() throws IOException {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(url);
httpPost.addHeader("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.107 Safari/537.36");
httpPost.addHeader("Accept", "*/*");
httpPost.addHeader("Accept-Encoding", "gzip, deflate, br");
httpPost.addHeader("Content-Type", "application/json");
httpPost.addHeader("Accept-Language", "zh-CN,zh;q=0.9,en;q=0.8");
httpPost.addHeader("Connection", "keep-alive");
JSONObject json = new JSONObject();
json.put("filePath","js");
json.put("projectId","61020ccdfd33d86b6abe8745");
json.put("type","fileFolder");
httpPost.setEntity(new StringEntity(json.toString(),"UTF-8"));
CloseableHttpResponse response = httpClient.execute(httpPost);
if (response.getStatusLine().getStatusCode() == 200) {
HttpEntity entity = response.getEntity();
String string = EntityUtils.toString(entity, "UTF-8");
System.out.println(string);
}
else
{
System.out.println("删除失败,请重试!!!");
}
response.close();
httpClient.close();
}
}