2 u011832730 u011832730 于 2014.08.31 20:03 提问

java新手,想问问有没有大牛给我解释一下这段代码,就是关于http报文传输的

需要添加httpmime包

这个是发post的method:
public static String sendPostRequest(String url, List nameValuePairs) {
// add code to validate required fields

    String res = null;

    try {
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(url);
        if (ListUtils.isNotEmpty(nameValuePairs)) {
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        }
        HttpResponse response = httpclient.execute(httppost);
        res = getResponseText(response);

        // add code check respond status

    } catch (ClientProtocolException e) {
        if (listener != null) {
            listener.onError(null);
        }
        CLog.e(HttpUtils.class, e.getMessage() + "");
    } catch (IOException e) {
        if (listener != null) {
            listener.onError(null);
        }
        CLog.e(HttpUtils.class, e.getMessage() + "");
    } catch (IllegalStateException e) {
        CLog.e(HttpUtils.class, e.getMessage());
        if (listener != null) {
            listener.onError(null);
        }
    }
    return res;
}

调用example:
List params = new LinkedList();

params.add(new BasicNameValuePair("pid", Integer.toString(pid)));

params.add(new BasicNameValuePair("comment", comment));

HttpUtils.sendPostRequest(“http://192.168.1.1/test.php”, params);

2个回答

c920816698
c920816698   2014.09.04 10:52

你最好先去了解一下http的请求方式,和请求步骤,在对着代码,查查API就能看懂了

hongjinusa
hongjinusa   2014.09.13 09:13

这有什么好解释的?

HttpPost httppost = new HttpPost(url);
用 url 新建一个 HTTP POST 的request

httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
添加 parmaters

HttpResponse response = httpclient.execute(httppost);
执行 HTTP POST 并得到 response

res = getResponseText(response);
把response 换成 可以阅读的 TEXT

其实在 response 里关键是要检查 status 是不是 200, 400, 500 等等

Csdn user default icon
上传中...
上传图片
插入图片
准确详细的回答,更有利于被提问者采纳,从而获得C币。复制、灌水、广告等回答会被删除,是时候展现真正的技术了!