HttpPost:
httpPost.addHeader("x-access-token",token);
public static String post(String strURL, String params, String token) {
System.out.println(strURL);
System.out.println(params);
Map<String,Object> map = new HashMap<>();
BufferedReader reader = null;
try {
URL url = new URL(strURL);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setUseCaches(false);
connection.setInstanceFollowRedirects(true);
connection.setRequestMethod("POST");
connection.addRequestProperty("x-access-token",token);
connection.setRequestProperty("Content-Type", "application/json");
connection.connect();
OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");
out.append(params);
out.flush();
out.close();
reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
String line;
String res = "";
while ((line = reader.readLine()) != null) {
res += line;
}
reader.close();
return res;
}catch (Exception e){
System.out.println(e.getMessage());
}
return "请求错误";
}
HttpURLConnection:
connection.addRequestProperty("x-access-token",token);
public static String sendRequest(String url, Map<String,Object> map,String token) {
String result = "";
try {
CloseableHttpClient client = null;
CloseableHttpResponse response = null;
List<BasicNameValuePair> parames = new ArrayList<>();
Set<String> keys = map.keySet();
for(String key:keys){
System.out.println("key值:"+key+" value值:"+map.get(key));
parames.add(new BasicNameValuePair(key, (String) map.get(key)));
}
try {
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(parames, "UTF-8"));
httpPost.addHeader("x-access-token",token);
client = HttpClients.createDefault();
response = client.execute(httpPost);
HttpEntity entity = response.getEntity();
result = EntityUtils.toString(entity);
System.out.println(result);
} finally {
if (response != null) {
response.close();
}
if (client != null) {
client.close();
}
}
} catch (Exception e) {
e.printStackTrace();
}
return result;
}