[英]settHeader (“content type”, “”) - confusion
我有一个函数,我想将两个变量发布到php端,在这两个变量匹配并且服务器处理了结果之后,我想以JSON返回结果。 到目前为止,我的set标头属性如下所示:
httppost.setHeader("Content-type", "application/json");
但是,当在Wikipedia上阅读时,我发现内容类型应该是application/x-www-form-urlencoded
并且要接受JSON,它应该是Accept: application/json
我希望对此更加清楚,如何修改代码以实现我想要的结果? 截至目前,我正在使用本地主机,而POST变量似乎未在php端传递。 以下是我的完整功能:
public void parse(String last, String pwd){
String lastIndex = last;
DefaultHttpClient http = new DefaultHttpClient(new BasicHttpParams());
System.out.println("URL is: "+CONNECT_URL);
HttpPost httppost = new HttpPost(CONNECT_URL);
httppost.setHeader("Content-type", "application/json");
try{
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("key", password));
nameValuePairs.add(new BasicNameValuePair("last_index", lastIndex));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
System.out.println("Post variables(Key): "+password+"");
System.out.println("Post variables(last index): "+lastIndex);
HttpResponse resp = http.execute(httppost);
HttpEntity entity = resp.getEntity();
ins = entity.getContent();
BufferedReader bufread = new BufferedReader(new InputStreamReader(ins, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while((line = bufread.readLine()) != null){
sb.append(line +"\n");
}
result = sb.toString();
System.out.println("Result: "+result);
// readAndParseJSON(result);
}catch (Exception e){
System.out.println("Error: "+e);
}finally{
try{
if(ins != null){
ins.close();
}
}catch(Exception smash){
System.out.println("Squish: "+smash);
}
}
// return result;
}
看来您的代码实际上正在执行该文章所描述的内容,除了
// httppost.setHeader("Content-type", "application/json");
httppost.setHeader("Content-Type", "application/x-www-form-urlencoded");
httppost.setHeader("Accept", "application/json");
您要在此处添加x-www-form-urlencoded内容
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
您遇到封顶问题。 尝试使用“ Content-Type”而不是“ Content-type” (或使用const HTTP.CONTENT_TYPE
)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.