您的位置:首页 > 理论基础 > 计算机网络

HttpClient和HttpURLConnection

2016-05-18 12:08 483 查看
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);
}
});
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  andorid