代码如下:
try {
HttpClient client = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
ArrayList<BasicNameValuePair> pairs = new ArrayList<BasicNameValuePair>();
Set<String> keys = params.keySet();
for(Iterator<String> i = keys.iterator(); i.hasNext();) {
String key = (String)i.next();
pairs.add(new BasicNameValuePair(key, params.get(key)));
}
UrlEncodedFormEntity p_entity = new UrlEncodedFormEntity(pairs, "utf-8");
httpPost.setEntity(p_entity);
HttpResponse response = client.execute(httpPost);
HttpEntity entity = response.getEntity();
content = entity.getContent();
在执行到HttpResponse response = client.execute(httpPost); 就出错了,求大神看下,或者给个简单的例子。
我只是来推荐一个第三方库的。。
http://loopj.com/android-async-http/
用它用来Post一个表单就这么简单:
RequestParams params = new RequestParams();
params.put("key", "value");
params.put("more", "data");
AsyncHttpClient client = new AsyncHttpClient();
client.post("http://www.google.com", params, new AsyncHttpResponseHandler() {
@Override
public void onSuccess(String response) {
System.out.println(response);
}
});
可以免去写一些代码,套一堆try-catch块,写处理网络线程和UI线程交互的代码的困扰。
Instagram都在用这个库。。。