问题描述
- java新手,想问问有没有大牛给我解释一下这段代码,就是关于http报文传输的
-
需要添加httpmime包这个是发post的method:
public static String sendPostRequest(String url, List nameValuePairs) {
// add code to validate required fieldsString 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);
解决方案
你最好先去了解一下http的请求方式,和请求步骤,在对着代码,查查API就能看懂了
解决方案二:
这有什么好解释的?
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 等等
时间: 2024-12-03 18:09:17