我有这个代码块,它向我的一个localhost端口发送一个post请求:
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或者应用程序没有向我显示任何结果。我的代码有问题吗?