发送post请求apache和java
我有一个向我的一个本地主机端口发送post请求的代码块:发送post请求apache和java,java,apache,http-post,Java,Apache,Http Post,我有一个向我的一个本地主机端口发送post请求的代码块: public String request(String name){ String responseString = null; List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("userName", name));
public String request(String name){
String responseString = null;
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("userName", name));
params.add(new BasicNameValuePair("passWord","123455"));
HttpPost post = new HttpPost("http://localhost:2332/getData/postData");
post.addHeader("Content-Type", "application/x-www-form-urlencoded");
post.setEntity(new StringEntity(URLEncodedUtils.format(params,"UTF-8"), HTTP.UTF_8));
responseString = execute(post,params.toString());
return responseString;
}
public String execute(HttpRequestBase requestBase, String params){
HttpClient httpClient = new DefaultHttpClient();
HttpResponse response = null;
String responseString = "";
try {
LOG.info("Request Method:{}",requestBase.getMethod());
LOG.info("Request Parameters:{}",params);
response = httpClient.execute(requestBase);
HttpEntity entity = response.getEntity();
responseString = EntityUtils.toString(entity);
} catch (IOException e) {
e.printStackTrace();
}
return responseString;
}
我认为这个代码块应该可以工作,因为我使用了一个教程作为参考,但是每当我运行我的应用程序时,responseString的值都是null,或者应用程序没有显示任何结果。我的代码有问题吗?您控制服务器吗?它是否向HTTP响应写入任何内容?是的,我的web应用程序控制服务器。预期的响应应该是json格式的数据。您可以打印实体的值吗?EntityUtils.toString。。如果为null,则只应返回null。我试图打印应用程序生成的状态代码,但它返回了302状态,这意味着问题在于处理服务器的另一个应用程序。我本以为HttpClient会自动跟踪302响应。您可能必须对此进行配置。