4

我正在尝试向 PHP 服务发送一个 http post 请求。以下是输入与一些测试数据的外观示例 在此处输入图像描述

我知道 PHP 关联数组的 Java 替代品是 HashMaps,但我想知道这可以用 NameValuePairs 来完成吗?格式化此输入并通过发布请求调用 PHP 服务的最佳方法是什么?

4

2 回答 2

4

扩展@Sash_KP 的答案,您也可以像这样发布nameValuePairs:

params.add(new BasicNameValuePair("Company[name]", "My company"));
params.add(new BasicNameValuePair("User[name]", "My Name"));
于 2014-09-08T03:16:55.607 回答
2

是的,这可以用NameValuePair.You 来完成。你可以有类似的东西

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.

于 2014-09-07T22:43:20.203 回答