Android HttpPost 请求问题

yzsunlight 2012-12-21 12:00:48
目前碰到一个HttpPost请求的问题,代码如下

@Override
public void onClick(View v) {

NameValuePair nameValuePair1 = new BasicNameValuePair("name", "zhangsan");
NameValuePair nameValuePair2 = new BasicNameValuePair("age", "18");
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(nameValuePair1);
nameValuePairs.add(nameValuePair2);

try {
HttpEntity requestHttpEntity = new UrlEncodedFormEntity(nameValuePairs,HTTP.UTF_8);
HttpPost httpPost = new HttpPost("http://www.*.cn/test.aspx");
httpPost.setEntity(requestHttpEntity);
HttpClient httpClient = new DefaultHttpClient();

//使用Http客户端发送请求对象
try {
System.out.println("1111111111111");
httpResponse = httpClient.execute(httpPost);
System.out.println("2222222222222");
httpEntity = httpResponse.getEntity();
System.out.println("33333333333333");
System.out.println(EntityUtils.toString(httpResponse.getEntity()));
System.out.println("44444444444444");
} catch (Exception e) {
e.printStackTrace();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}

}

经过测试
----------------
在Android2.3、模拟器及手机上没出现问题,是可以正常输出的
----------------
在android2.2手机及模拟器,android2.1模拟器上运行到
System.out.println(EntityUtils.toString(httpResponse.getEntity()));
就卡不会立即运行了,等待很久.偶尔弹出提示应用程序无响应的提示,偶尔也会输出“44444444444444”,但System.out.println(EntityUtils.toString(httpResponse.getEntity()));内容始终输不出来,正常情况下是会有响应内容的。

因此又在android2.2手机及模拟器,android2.1模拟器上做了几个测试
测试一:
如果把http://www.*.cn/test.aspx改成http://www.baidu.com,是可以正常运行的
测试二:
如果把httpPost.setEntity(requestHttpEntity); 这行注释掉,还是请求代码里的URL,也就是post请求不带请求参数,也是可以正常运行的。
请各位指点!
...全文
415 11 打赏 收藏 转发到动态 举报
写回复
用AI写文章
11 条回复
切换为时间正序
请发表友善的回复…
发表回复
zhangwenbin1818 2015-03-20
  • 打赏
  • 举报
回复
不错不错不错不错不错不错不错不错不错不错不错不错不错不错不错不错不错
yzsunlight 2012-12-25
  • 打赏
  • 举报
回复
引用 7 楼 KPRF2009 的回复:
建议不要把网络请求的代码放在主线程中。。。
引用 9 楼 gxhea 的回复:
主线程不能访问网络,最好用子线程
目前确实用的子线程在走

 new Thread(){
        	public void run() {

具体代码实现。。。。

  • 打赏
  • 举报
回复
主线程不能访问网络,最好用子线程
问答小助手 2012-12-24
  • 打赏
  • 举报
回复
你需要在单独的线程中创建HttpPost。如果用户点击,会冻结UI。我找到一个HttpPost示例代码。
public class ConnectionManager{
    private Context context;

    public ConnectionManager(Context ctx){
        this.context = ctx;
    }

    public boolean networkInfo(){
        ConnectivityManager connMgr = (ConnectivityManager)this.context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
        if (networkInfo != null && networkInfo.isConnected()) {
            return true;
        } else {
            return false;
        }
    }

    public void showAlert(String title,String message){
        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
                this.context);

        // set title
        alertDialogBuilder.setTitle(title);

        // set dialog message
        alertDialogBuilder
        .setMessage(message)
        .setCancelable(false)
        .setNegativeButton("OK",new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog,int id) {
                // if this button is clicked, just close
                // the dialog box and do nothing
                dialog.cancel();
            }
        });

        // create alert dialog
        AlertDialog alertDialog = alertDialogBuilder.create();

        // show it
        alertDialog.show();

    }
    public String execute_get(String url) {
        // TODO Auto-generated method stub
        HttpResponse response  = null;
        String str_response = "";               

        if(networkInfo()){
            DefaultHttpClient httpsClient = getHTTPSClient();

            try {
                HttpGet httpget = new HttpGet(url);
                response = httpsClient.execute(httpget);
                if (response != null) {
                    str_response = EntityUtils.toString(response.getEntity());
                    Log.d("Connection Manager","Response: "+str_response);
                }
            }catch(Exception e){
                e.printStackTrace();
            }
        }else{
            showAlert("Connection Error","Please connect to wifi/3g to continue");
        }

        return str_response;
    }

    public DefaultHttpClient getHTTPSClient() {
        SchemeRegistry schemeRegistry = new SchemeRegistry();
        schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));

        HttpParams params = new BasicHttpParams();
        params.setParameter(ConnManagerPNames.MAX_TOTAL_CONNECTIONS, 30);
        params.setParameter(ConnManagerPNames.MAX_CONNECTIONS_PER_ROUTE, new ConnPerRouteBean(30));
        params.setParameter(HttpProtocolParams.USE_EXPECT_CONTINUE, false);
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);

        ClientConnectionManager cm = new SingleClientConnManager(params, schemeRegistry);
        DefaultHttpClient httpsClient= new DefaultHttpClient(cm, params);
        return httpsClient;
    }

    public String execute_post(String url,String request){
        HttpResponse response  = null;
        String str_response = "";               
        if(networkInfo()){
            DefaultHttpClient httpsClient = getHTTPSClient();

            try {
                HttpPost httppost = new HttpPost(url);

                List<BasicNameValuePair> nameValuePairs = new ArrayList<BasicNameValuePair>(2);
                nameValuePairs.add(new BasicNameValuePair("jsonData", request));
                httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));   
                response = httpsClient.execute(httppost);

                if (response != null) {
                    str_response = EntityUtils.toString(response.getEntity());
                    Log.d("ConnectionManager", "Response: "+str_response);
                }
            }catch(Exception e){
                e.printStackTrace();
            }
        }else{
            showAlert("Connection Error","Please connect to wifi/3g to continue");
        }
        return str_response;
    }   


}


// Use the above like this 

                              new Thread() {
                    @Override
                    public void run() {
                        try {
                            String input = "Your post data"
                            Log.d("POSTDATA",input);
                            String response = execute_post(URLS.LOGIN_AUTH,input);

                            Message responseMsg = new Message();
                            Bundle b = new Bundle();
                            b.putString("response", response);
                            responseMsg.setData(b);

                            handler.sendMessage(responseMsg);
                        }catch(Exception e){

                        }
                    }
                }.start();
KPRF2009 2012-12-23
  • 打赏
  • 举报
回复
建议不要把网络请求的代码放在主线程中。。。
  • 打赏
  • 举报
回复
是不是和手机上网速度有关,这个联网操作放在线程中走异步
yzsunlight 2012-12-22
  • 打赏
  • 举报
回复
引用 4 楼 zhangjingxuan891 的回复:
走个断点看看
如何走断点? 只能看logcat吧
zhangjingxuan891 2012-12-21
  • 打赏
  • 举报
回复
走个断点看看
搬不搬砖 2012-12-21
  • 打赏
  • 举报
回复
引用 2 楼 yzsunlight 的回复:
试了 情况还是一样
EntityUtils.toString是需要从InputStream中读取数据的,是不是你的网站或网络有问题,导致一直在等待数据
yzsunlight 2012-12-21
  • 打赏
  • 举报
回复
试了 情况还是一样
roger_ding 2012-12-21
  • 打赏
  • 举报
回复
把System.out.println(EntityUtils.toString(httpResponse.getEntity()));换成 System.out.println(EntityUtils.toString(httpEntity));试试

80,337

社区成员

发帖
与我相关
我的任务
社区描述
移动平台 Android
androidandroid-studioandroidx 技术论坛(原bbs)
社区管理员
  • Android
  • yechaoa
  • 失落夏天
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧