老版:PostMethod
- public class HttpTests {
- /**
- * @param args
- * @throws Exception
- */
- public static void main(String[] args) throws Exception {
- HttpClient httpclient = new HttpClient();
- PostMethod httpPost =new PostMethod("******/abc");
- NameValuePair[] param = { new NameValuePair("username", "vip")};
- httpPost.setRequestBody(param);
- httpclient.executeMethod(httpPost);
- }
- }
新版:HttpPost
public static String getMes(String url, String params) {
CloseableHttpClient client = HttpClients.createDefault();
HttpPost htPost = new HttpPost(url);
String backMes = null;
try {
htPost.setHeader("content-type", "application/json");
StringEntity reqEntity = new StringEntity(params);
htPost.setEntity(reqEntity);
HttpResponse httpResponse = client.execute(htPost);
HttpEntity entity = httpResponse.getEntity();
backMes = EntityUtils.toString(entity, "UTF-8").toString();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
client.close();
client = null;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return backMes;
}