HttpURLConnection +HttpClient

来源:互联网 发布:淘宝详情页怎么加链接 编辑:程序博客网 时间:2024/06/06 03:07

HttpURLConnection    get 请求

package com.bwei.day04_httpurlconnection_get;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {

    public static final int SHOW_RESPONSE = 0;

    private Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
            case SHOW_RESPONSE:
                String response = (String) msg.obj;
                // 在这里进行UI操作,将结果显示到界面上
                responText.setText(response);
            }
        };
    };

    private TextView responText;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        responText = (TextView) findViewById(R.id.respon);

    }

    // get请求服务器
    public void logGet(View v) {

        if (v.getId() == R.id.button1) {
            sendRequestWithHttpURLConnection();

        }

    }

    private void sendRequestWithHttpURLConnection() {
        // 开启线程来发起网络请求
        

        new Thread() {
            
            private HttpURLConnection connection;

            public void run() {
                try {
                    final String path = "http://www.baidu.com";
                    // 创建URL对象
                    URL url = new URL(path);
                    connection = (HttpURLConnection) url.openConnection();
                    // 设置请求方式
                    connection.setRequestMethod("GET");
                    // 设置请求超时时间
                    connection.setConnectTimeout(8 * 1000);
                    // 设置超时读取时间
                    connection.setReadTimeout(8 * 1000);
                    // 得到服务器返回的请求码
                    //int responseCode = connection.getResponseCode();

                    InputStream is = connection.getInputStream();
                    BufferedReader reader=new BufferedReader(new InputStreamReader(is));
                    StringBuilder builder=new StringBuilder();
                    String line;
                    while((line=reader.readLine())!=null){
                        builder.append(line);
                        
                    }
                    Message msg=new Message();
                    msg.what=SHOW_RESPONSE;
                    //将服务器返回的结果存放到msg中
                    msg.obj=builder.toString();
                    handler.sendMessage(msg);
                    
                    
                    
                    

                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }finally{
                    if(connection!=null){
                        //关闭连接
                        connection.disconnect();
                    }
                }

            };
        }.start();
    }

}


HttpClient     post请求


package com.bwei.utils;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import android.content.Context;

import com.bwei.vo.Goods;

public class EndWorkUtils {
    
    public static String getPoststr(Context context){
        
        String path="http://japi.juhe.cn/health_knowledge/categoryList";
        HttpClient client=new DefaultHttpClient();
        
        HttpPost post=new HttpPost(path);
        
        
        try {
            List<NameValuePair> parameters=new ArrayList<NameValuePair>();
            parameters.add(new BasicNameValuePair("key", "30275f5e0540c7e05e66e9641960c0c6"));
            HttpEntity entity = new UrlEncodedFormEntity(parameters, "utf-8");
            post.setEntity(entity);
            HttpResponse response = client.execute(post);
            
            int statusCode = response.getStatusLine().getStatusCode();
            if(statusCode==200){
                InputStream is = response.getEntity().getContent();
                ByteArrayOutputStream baos=new ByteArrayOutputStream();
                byte[] arr=new byte[1024];
                int len;
                while((len=is.read(arr))!=-1){
                    baos.write(arr, 0, len);
                }
                return baos.toString();
            }
            
            
            
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
        
        
        return null;
        
    }

}


HttpClient       get请求


package com.bwei.utils;

import java.io.IOException;

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;

public class EntWorkUtils {
    
    public static String getStr(String path){
        HttpClient client=new DefaultHttpClient();
        HttpGet get=new HttpGet(path);
        try {
            HttpResponse response = client.execute(get);
            int code = response.getStatusLine().getStatusCode();
            if(code==200){
                HttpEntity entity = response.getEntity();
                String json = EntityUtils.toString(entity, "gbk");
                return json;
            }
            
            
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
        
        
        return null;
        
    }

}



1 0