我正在尝试向PHP服务发送http post请求。下面是一些输入可能与某些测试数据相关的示例
我知道PHP关联数组的Java替代品是HashMaps,但我想知道这可以用NameValuePairs完成吗?格式化此输入并通过post请求调用PHP服务的最佳方法是什么?
答案 0 :(得分:4)
扩展@Sash_KP的答案,您也可以像这样发布nameValuePairs:
params.add(new BasicNameValuePair("Company[name]", "My company"));
params.add(new BasicNameValuePair("User[name]", "My Name"));
答案 1 :(得分:2)
是的,可以使用NameValuePair
完成此操作。您可以使用
List<NameValuePair> params;
//and when making `HttpPost` you can do
HttpPost httpPost = new HttpPost("Yoururl");
httpPost.setEntity(new UrlEncodedFormEntity(params));
//and while building parameters you can do somethin like this
params.add(new BasicNameValuePair("name", "firemanavan"));
params.add(new BasicNameValuePair("cvr", "1245678"));
....
这是一个很好的解析方法,你可以使用它。
public JSONObject getJSONFromUrl(String url, List<NameValuePair> params) {
InputStream is = null;
String json = "";
JSONObject jObj = null;
// Making HTTP request
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
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.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 jObj;
}
你可以简单地使用像
这样的东西getJSONFromUrl("YourUrl", params);
现在这只是一个基本概念,说明如何使用NameValuePair
实现此目的。您将需要更多的解决方法来完全按照您的意愿实现,但这应该为您提供基本的想法。希望这有助于