//url:目标地址和端口,postString:字符串内容
public static String doPostWithoutKey(String url,String postString) throws IOException {
HttpClient client = new HttpClient();
//请求 网络上的服务, 用这种方式请求本地,返回一个Html页面
PostMethod method = new PostMethod(url);
HttpConnectionManagerParams managerParams = client.getHttpConnectionManager().getParams();
//设置连接超时时间为2秒
managerParams.setConnectionTimeout(2000);
method.setRequestHeader("Content-type", "application/json; charset=UTF-8");
method.setRequestHeader("Accept", "application/json; charset=UTF-8");
//设置重试
method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(0,false));
method.setRequestBody(postString);
try{
client.executeMethod(method);
}catch (Exception e){}
return null;
}
Http的Post请求基本使用就是这样,可以在项目里直接使用。
public static void main(String[] args){ try { Http.doPostWithoutKey("http://192.168.1.207:8080/","1111"); } catch (IOException e) { e.printStackTrace(); } }
运行main在网络测试助手中可以接受到发送的数据