我尝试使用以下方法将数据从Android应用程序发送到服务器:
public JSONObject getJSONFromUrl(String url, List<NameValuePair> params) {
try{
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
for (int i=0; i<params.size(); i++) {
Log.v("askj",params.get(i).toString());
}
httpPost.setEntity(new UrlEncodedFormEntity(params));
try {
Log.v("askj","HTTP Entity : " + convertStreamToString(httpPost.getEntity().getContent()));
}catch (Exception e){
e.printStackTrace();
}
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
Log.v("askj",json);
Log.e("JSON", json);
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
我确信我确保我的参数正确,网址很好,但这段代码httpPost.setEntity(new UrlEncodedFormEntity(params));
无法正常工作。正在访问的网址没有这些参数。 httpClient.execute(httpPost);
只是在没有任何参数的情况下访问初始URL。我怎么解决这个问题?我尝试使用URI而不是setEntity,但我不知道如何一次追加可变数量的参数。
编辑:我使用Postman测试了我的服务,网站可以处理POST请求,因此问题在于JSONParser。
答案 0 :(得分:0)
尝试指定这样的编码格式:
httpPost.setEntity(new UrlEncodedFormEntity(params, "utf-8"));