android post 请求 报出异常 java.net.UnknownHostException: www.****.com

来源:互联网 发布:js替换某个字符串 编辑:程序博客网 时间:2024/06/01 17:32
交代背景,在安卓中做post提交的时候一直报 java.net.UnknownHostException的异常,在网上找了很久都没有看到一个非常有效的解决,什么ping了,检查网络了,因为这是同事在自己机器起的一个服务,所以忽然想到说不得是域名访问不了,然后换成了ip访问,ok!过了。有可能是其他的问题,但是当下算是解决了一个大问题。以下是访问代码:
import java.io.IOException;import java.util.ArrayList;import java.util.List;import java.util.Map;import org.apache.http.HttpResponse;import org.apache.http.NameValuePair;import org.apache.http.client.ClientProtocolException;import org.apache.http.client.entity.UrlEncodedFormEntity;import org.apache.http.client.methods.HttpPost;import org.apache.http.impl.client.DefaultHttpClient;import org.apache.http.message.BasicNameValuePair;import org.apache.http.util.EntityUtils;public class PostUtils {public static String submitPostData(Map <String, String> mapParams,String encode,String urlStr) {String result = "";// 1,创建HttpPost对象HttpPost httpPost = new HttpPost(urlStr);//2, 设置HTTP POST请求参数 须用NameValuePair对象List<NameValuePair> params = new ArrayList<NameValuePair>();for (String key : mapParams.keySet()) {params.add(new BasicNameValuePair(key, mapParams.get(key)));}HttpResponse httpResponse = null;try {//3,设置httpPost请求参数httpPost.setEntity(new UrlEncodedFormEntity(params, encode));httpResponse = new DefaultHttpClient().execute(httpPost);if (httpResponse.getStatusLine().getStatusCode() == 200) {// 第三步,getEntity来获得返回结果result = EntityUtils.toString(httpResponse.getEntity());}} catch (ClientProtocolException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}return result;}}

0 0
原创粉丝点击