static HttpClient httpclient = new DefaultHttpClient();
static HttpPost httppost = new HttpPost("http://servername:6405/biprws/logon/long");
public static void main(String[] args) throws ClientProtocolException, IOException {
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("userName", "Administrator"));
postParameters.add(new BasicNameValuePair("password", "test"));
postParameters.add(new BasicNameValuePair("auth", "secEnterprise"));
httppost.setEntity(new UrlEncodedFormEntity(postParameters));
httppost.addHeader("accept", "application/json");
httppost.addHeader("Content-Type", "application/json");
HttpResponse response = httpclient.execute(httppost);
Header s = response.getFirstHeader("logontoken");
String s1 = s.getValue();
System.out.println(s1);// null pointer exception here
}
运行上面的代码我无法将请求主体添加到POST请求中。我怎样才能做到这一点?
我遵循的替代方法:
HttpClient client1 = new DefaultHttpClient();
HttpPost post = new HttpPost("http://servername:6405/biprws/logon/long");
String json = "{\"UserName\":\"Administrator\",\"Password\":\"test\",\"Auth\":\"secEnterprise\"}";
StringEntity entity = new StringEntity(json,"UTF-8");
entity.setContentType("application/json");
post.setEntity(entity);
System.out.println(entity);
post.setHeader("Accept", "application/json");
HttpResponse response = client1.execute(post);
BufferedReader rd1 = new BufferedReader(
new InputStreamReader(response.getEntity().getContent()));
String result1 = null;
String line1 = "";
result1 = rd1.readLine();
System.out.println(result1);
我仍然无法提出要求。
答案 0 :(得分:0)
您成功收到 不 包含&#34; logontoken&#34;的回复头。很可能是因为响应不是HTTP 200 OK响应。为什么?我们不知道,这完全取决于您的服务器在HTTP之上实现的协议。
话虽如此,使用httppost.setEntity(new UrlEncodedFromEntity(postParameters))
和httppost.addHeder("Content-Type", "application/json")
对我来说并不合适。 URL编码的表单实体不是json内容类型。因此,要么将post参数转换为json,要么丢失内容类型标题。