【发布时间】:2014-07-30 04:56:42
【问题描述】:
我有一个函数,我想将两个变量发布到 php 端,在这两个变量匹配并且服务器处理结果之后,我想以 JSON 格式返回结果。截至目前,我设置的标头属性如下所示:
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;
}
【问题讨论】: