2,204
社区成员
发帖
与我相关
我的任务
分享
HttpClient httpClient = new DefaultHttpClient();
HttpPost postRequest = new HttpPost("http://103.247.176.245:8081/tool/syllabletag/");
MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
try {
reqEntity.addPart("csrfmiddlewaretoken", new StringBody(getPageToken()));
reqEntity.addPart("input_text", new StringBody("hahhahhahahahah"));
reqEntity.addPart("output_text", new StringBody(""));
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
postRequest.setEntity(reqEntity);
HttpResponse response;
try {
response = httpClient.execute(postRequest);
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
String sResponse;
StringBuilder s = new StringBuilder();
while ((sResponse = reader.readLine()) != null) {
s = s.append(sResponse);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String boundary = "----WebKitFormBoundarygmk3KBUQwymfMc8A";
//请求地址
String url = "https://url";
String param = "";
param +="--"+boundary+"\r\n";
param += "Content-Disposition: form-data; name=\"account\""+"\r\n\r\n";
//参数account
param+= "account"+"\r\n";
param +="--"+ boundary+"\r\n";
param += "Content-Disposition: form-data; name=\"password\""+"\r\n\r\n";
//参数password
param += "password"+"\r\n";
param+="--"+boundary+"--";
//请求头,看情况自己加
Map<String,String> headMap = new HashMap<>();
headMap.put("Content-Type", "multipart/form-data; boundary=----WebKitFormBoundarygmk3KBUQwymfMc8A");
Map<String,Object> reMap = HttpClientUtil.doMultipartFormDataPost(url,param,headMap);
public static Map<String, Object> doMultipartFormDataPost(String url, String param, Map<String, String> headParam) {
// TODO Auto-generated method stub
// 创建Httpclient对象
Map<String,Object> resultMap = new HashMap<>();
String resultString = "";
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null;
try {
// 创建Http Post请求
HttpPost httpPost = new HttpPost(url);
// 创建请求内容
StringEntity entity = new StringEntity(param, ContentType.MULTIPART_FORM_DATA);
httpPost.setEntity(entity);
for(String key:headParam.keySet()) {
httpPost.addHeader(key,headParam.get(key));
}
// 执行http请求
response = httpClient.execute(httpPost);
resultString = EntityUtils.toString(response.getEntity(), "utf-8");
Header[] headers =response.getHeaders("Set-Cookie");
Map<String,String> headMap = new HashMap<>();
for(int i=0;i<headers.length;i++) {
headMap.put(headers[i].getElements()[0].getName(), headers[i].getElements()[0].getValue());
}
resultMap.put("headMap", headMap);
resultMap.put("result", resultString);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
response.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return resultMap;
}
maven依赖
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
</dependency>