HttpClient和HttpURLConnection

HttpClient

package com.example.day06_httpclient;

import java.io.IOException;
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.client.methods.HttpUriRequest;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.DefaultClientConnection;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;

public class MainActivity extends Activity {
	String key = "3ac9f31ff66b9746539472887b3799c3";
	String path = "http://web.juhe.cn:8080/constellation/getAll";
	String get_path = "http://web.juhe.cn:8080/constellation/getAll?consName=狮子座&type=today&key="
			+ key;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
       new Thread(){

		@Override
		public void run() {
			// TODO Auto-generated method stub
//			get();
			post();
		}

    	   
       }.start();
    }


	protected void post() {
		// TODO Auto-generated method stub
		HttpClient httpClient = new DefaultHttpClient();
		HttpPost httpPost = new HttpPost(path);
		try {
			List<NameValuePair> parameters = new ArrayList<NameValuePair>();
			parameters.add(new BasicNameValuePair("consName", "狮子座"));
			parameters.add(new BasicNameValuePair("type", "year"));
			parameters.add(new BasicNameValuePair("key", key));
			// 实体数据中需要放入集合数据
			HttpEntity entity = new UrlEncodedFormEntity(parameters, "utf-8");
			// post 中应该包含实体数据
			httpPost.setEntity(entity );
			// 用带有地址的httppost请求
			HttpResponse httpResponse = httpClient.execute(httpPost);
			if(httpResponse.getStatusLine().getStatusCode()==200){
				System.out.println("连接成功");
				HttpEntity httpEntity = httpResponse.getEntity();
				System.out.println(EntityUtils.toString(httpEntity));
			}else{
				System.out.println("连接失败");
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
		}
	}


	private void get() {
		// 建立请求
		HttpClient httpClient = new DefaultHttpClient();
		// 建立请求类型
		HttpGet httpGet = new HttpGet(get_path);
		try {
			// 执行请求的地址 获得响应的东西
			HttpResponse httpResponse = httpClient.execute(httpGet);
			
			// 获取响应的实体
			HttpEntity entity = httpResponse.getEntity();
			String string = EntityUtils.toString(entity);
			System.out.println(string);
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
HttpURLConnection

package com.example.day06_httpclient;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.text.BreakIterator;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;

public class HttpURLConnectionActivity extends Activity {
	String get_path = "http://web.juhe.cn:8080/constellation/getAll?consName=%E7%8B%AE%E5%AD%90%E5%BA%A7&type=today&key=3ac9f31ff66b9746539472887b3799c3";
	private BufferedReader br;
	private HttpURLConnection httpURLConnection;
	String path = "http://web.juhe.cn:8080/constellation/getAll";

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

			@Override
			public void run() {
//				getData();
				getDataPost();
			}

		}.start();
	}

	protected void getDataPost() {
		// TODO Auto-generated method stub
		try {
			URL url = new URL(path);
			HttpURLConnection httpURLConnection = (HttpURLConnection) url
					.openConnection();
			//设置连接
			httpURLConnection.setConnectTimeout(5000);
			httpURLConnection.setReadTimeout(5000);
			httpURLConnection.setRequestMethod("POST");
			
			OutputStream outputStream = httpURLConnection.getOutputStream();
			// 建立连接
			httpURLConnection.connect();
			
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private void getData() {
		URL url;
		try {
			url = new URL(get_path);
			httpURLConnection = (HttpURLConnection) url.openConnection();

			// 设置连接的限制
			httpURLConnection.setConnectTimeout(5000);
			httpURLConnection.setReadTimeout(5000);
			httpURLConnection.setRequestMethod("GET");

			// 开始链接
			httpURLConnection.connect();

			//
			int responseCode = httpURLConnection.getResponseCode();
			if (responseCode == 200) {
				System.out.println("连接成功");
				InputStream inputStream = httpURLConnection.getInputStream();
				br = new BufferedReader(new InputStreamReader(inputStream,
						"utf-8"));
				String str = null;
				StringBuffer sb = new StringBuffer();
				while ((str = br.readLine()) != null) {
					sb.append(str.trim());
				}
				br.close();
				System.out.println(sb.toString());
			}
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		// TODO Auto-generated method stub
		catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {

		}
	}

}

xutil 连接 最简单的

// 通过网址获得信息
	private void getData(final int i, String path) {
		HttpUtils httpUtils = new HttpUtils();
		// 配置当前网络缓存到期时间 (0秒内数据那缓存数据)默认60s
		httpUtils.configCurrentHttpCacheExpiry(0);
		// 开始连接,RequestCallBack<T>是得到的数据类型
		httpUtils.send(HttpMethod.GET, path, new RequestCallBack<String>() {

			private NewsDetails newsDetails;

			@Override
			public void onFailure(HttpException arg0, String arg1) {
				// 失败的方法
				Toast.makeText(context, "网络连接错误,请稍后再试", 0).show();
			}

			@Override
			public void onSuccess(ResponseInfo<String> arg0) {
				// 成功执行方法
				String result = arg0.result;
                               //  转化为流的方法
                               ByteArrayInputStream inputStream = new ByteArrayInputStream(
                        result.getBytes());
				// 这里是在子线程中,所以需要handler
				handler.sendEmptyMessage(i);
			}
		});
	}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值