Android的HttpConnection和HttpClient发送请求

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/sinat_27362429/article/details/45070589
package com.mine.networktest;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity implements OnClickListener {

    public static final int SHOW_RESPONSE = 0;
    public static final int SHOW_HttpClient = 0;
    private Button sendRequest_btn;
    private Button httpClient_btn;
    private TextView responseTest;

    private Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {

            switch (msg.what) {
            case SHOW_RESPONSE:
                String response = (String) msg.obj;
                // 在这里进行UI操作,将结果显示到界面上
                responseTest.setText(response);
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        sendRequest_btn = (Button) findViewById(R.id.send_request);
        httpClient_btn = (Button)findViewById(R.id.http_client);
        responseTest = (TextView) findViewById(R.id.response_text);
        sendRequest_btn.setOnClickListener(this);
        httpClient_btn.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        switch (v.getId() ) {
        case R.id.send_request:
            sendRequestWithHttpURLConnection();
            break;
        case R.id.http_client:
            sendRequestWithHttpClient();
            break;
        default:
            break;
        }

    }

    private void sendRequestWithHttpClient() {
        // TODO Auto-generated method stub
        new Thread(new Runnable() {

            @Override
            public void run() {
                // TODO Auto-generated method stub
                HttpClient httpClient = new DefaultHttpClient();
                HttpGet httpGet = new HttpGet("http://www.baidu.com");
                try {
                    HttpResponse httpResponse = httpClient.execute(httpGet);
                    if (httpResponse.getStatusLine().getStatusCode()==200) {
                        //请求和响应都成功了
                        HttpEntity entity = httpResponse.getEntity();
                        String response = EntityUtils.toString(entity, "utf-8");
                        Message msg = new Message();
                        msg.what = SHOW_RESPONSE;
                        //将服务器返回的结果放在Message中
                        msg.obj = response.toString();
                        handler.sendMessage(msg);
                    }
                } catch (ClientProtocolException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        }).start();
    }

    private void sendRequestWithHttpURLConnection() {
        // 开启线程发送网络请求
        new Thread(new Runnable() {

            @Override
            public void run() {

                HttpURLConnection connection = null;
                try {
                    URL url = new URL("http://www.haidu.com");
                    connection = (HttpURLConnection) url.openConnection();
                    connection.setRequestMethod("GET");
                    connection.setConnectTimeout(8000);
                    connection.setReadTimeout(8000);
                    InputStream is = connection.getInputStream();
                    // 对获取到的输入流进行读取
                    BufferedReader reader = new BufferedReader(
                            new InputStreamReader(is));
                    StringBuilder response = new StringBuilder();
                    String line;
                    while ((line = reader.readLine()) != null) {
                        response.append(line);
                    }
                    Message msg = new Message();
                    msg.what = SHOW_RESPONSE;
                    // 将服务器返回的结果保存在message中
                    msg.obj = response.toString();
                    handler.sendMessage(msg);
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (connection != null) {
                        connection.disconnect();
                    }
                }
            }
        }).start();
    }
}

展开阅读全文

android发送请求失败

11-03

下面是一个执行访问外网接口返回数据的一个方法rn[code=java]rnprivate String getPDAServerData(String url)rn HttpClient client = new DefaultHttpClient();rn HttpPost request;rn String out="";rn try rn request = new HttpPost(new URI(url));rn HttpResponse response = client.execute(request);rn // 判断请求是否成功rn if (response.getStatusLine().getStatusCode() == 200) rn HttpEntity entity = response.getEntity();rn if (entity != null) rn out = EntityUtils.toString(entity);rn //new AlertDialog.Builder(this).setMessage(out).create().show();rn rn rnrn catch (URISyntaxException e) rn e.printStackTrace();rn catch (ClientProtocolException e) rn e.printStackTrace();rn catch (IOException e) rn e.printStackTrace();rn rn return out;rn rnprotected void onCreate(Bundle savedInstanceState) rn super.onCreate(savedInstanceState);rn setContentView(R.layout.activity_main);rn textView1 = (TextView)this.findViewById(R.id.msg);rn // id,title,thumb,description,inputtimern String str = getPDAServerData(url); rn String []arr = str.split("&");//这里是自定义的字符解析,可以忽略rn String html = "";rn for(int i=0;i"+arr2[1];rn if(i%2!=0)rn html+=" ";rn rn CharSequence charSequence = Html.fromHtml(html);rn textView1.setText(charSequence);rn rn rn[/code]rn运行虚拟机以后,提示 HttpResponse response = client.execute(request); 报错了rnAndroidManifest.xml中增加了下面这句话,还是一样。不知道还需要做什么才不报错?rn 论坛

没有更多推荐了,返回首页