HttpClient的GET和POST解析
来源:互联网 发布:中国特色社会主义 知乎 编辑:程序博客网 时间:2024/06/05 17:27
package com.kson.httpclient;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
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 java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import javax.net.ssl.HandshakeCompletedListener;
public class HttpActivity extends AppCompatActivity {
private final String IMG_URL = "http://img4.imgtn.bdimg.com/it/u=1968856895,1816029947&fm=26&gp=0.jpg";
private final int SUCCESS = 0;
private final int FAIL = -1;
private String response_msg = "";
private final String GETURL = "http://v.juhe.cn/toutiao/index?type=top&&key=22a108244dbb8d1f49967cd74a0c144d";
private final String POSTURL = "http://v.juhe.cn/toutiao/index";
private ImageView mImgIv;
Handler mHttpClientHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
int what = msg.what;
switch (what) {
case SUCCESS:
String result = (String) msg.obj;
Toast.makeText(HttpActivity.this, result, Toast.LENGTH_SHORT).show();
parseData(result);
break;
case FAIL:
Toast.makeText(HttpActivity.this, response_msg, Toast.LENGTH_SHORT).show();
break;
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_http);
initView();
}
private void initView() {
mImgIv = (ImageView) findViewById(R.id.iv_img);
}
/**
* 解析返回的json字符串
*
* @param result
*/
private void parseData(String result) {
// TODO: 2017/8/7 同学们实现
}
/**
* get请求
*
* @param v
*/
public void getClick(View v) {
//开启子线程,处理get请求
new Thread(new Runnable() {
@Override
public void run() {
getNews();
}
}).start();
}
/**
* post请求
*
* @param v
*/
public void postClick(View v) {
//开启子线程,处理post请求
new Thread(new Runnable() {
@Override
public void run() {
postNews("top", "22a108244dbb8d1f49967cd74a0c144d");
}
}).start();
}
/**
* 下载图片
* @param v
*/
public void imgClick(View v){
//开启子线程,处理post请求
new Thread(new Runnable() {
@Override
public void run() {
downloadImg();
}
}).start();
}
/**
* get请求获取新闻数据
*/
private void getNews() {
StringBuffer result = new StringBuffer();
//创建HttpClient对象,打开一个浏览器
HttpClient httpClient = new DefaultHttpClient();
//创建HttpGet对象,get请求的对象,传入url
HttpGet httpGet = new HttpGet(GETURL);
try {
//发起请求,拿到HttpResponse对象,这个对象是服务器返回的数据对象
HttpResponse httpResponse = httpClient.execute(httpGet);
//根据响应行,拿到响应吗
int responseCode = httpResponse.getStatusLine().getStatusCode();
response_msg = httpResponse.getStatusLine().getReasonPhrase();
if (200 == responseCode) {//如果响应码是200,则请求成功,否则失败
//得到返回的实体对象
HttpEntity entity = httpResponse.getEntity();
InputStream in = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line = null;
while ((line = reader.readLine()) != null) {
result.append(line);
}
Log.d("result--------", result.toString());
Message msg = new Message();
msg.what = SUCCESS;
msg.obj = result.toString();
mHttpClientHandler.sendMessage(msg);
} else {//请求失败,处理请求失败逻辑
Message msg = new Message();
msg.what = FAIL;
mHttpClientHandler.sendMessage(msg);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
httpClient.getConnectionManager().shutdown();
}
}
/**
* post请求
*/
private void postNews(String type, String key) {
String result = null;
HttpClient client = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(POSTURL);
try {
//封装传递参数的集合
List<NameValuePair> parameters = new ArrayList<NameValuePair>();
//往这个集合中添加你要传递的参数
parameters.add(new BasicNameValuePair("type", type));
parameters.add(new BasicNameValuePair("key", key));
//创建传递参数封装 实体对象
UrlEncodedFormEntity encodeEntity = new UrlEncodedFormEntity(parameters, "UTF-8");//设置传递参数的编码
//把实体对象存入到httpPost对象中
httpPost.setEntity(encodeEntity);
//3. 调用第一步中创建好的实例的 execute 方法来执行第二步中创建好的 method 实例
HttpResponse response = client.execute(httpPost); //HttpUriRequest的后代对象 //在浏览器中敲一下回车
//根据响应行,拿到响应吗
int responseCode = response.getStatusLine().getStatusCode();
response_msg = response.getStatusLine().getReasonPhrase();
//4. 读 response
if (200 == responseCode) {//如果响应码是200,则请求成功,否则失败
//得到返回的实体对象
HttpEntity entity = response.getEntity();
InputStream in = entity.getContent();
ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
int length = 0;
byte[] buffer = new byte[1024];
while ((length = in.read(buffer)) != -1) {
byteOut.write(buffer, 0, length);
}
result = byteOut.toString("utf-8");
System.out.println("result=====" + result);
Message msg = new Message();
msg.what = SUCCESS;
msg.obj = result;
mHttpClientHandler.sendMessage(msg);
} else {//请求失败,处理请求失败逻辑
Message msg = new Message();
msg.what = FAIL;
mHttpClientHandler.sendMessage(msg);
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 图片下载
*/
private void downloadImg() {
try {
URL u = new URL(IMG_URL);
HttpURLConnection connection = (HttpURLConnection) u.openConnection();
connection.connect();
if (200 == connection.getResponseCode()) {
InputStream in = connection.getInputStream();
final Bitmap bitmap = BitmapFactory.decodeStream(in);
mImgIv.post(new Runnable() {
@Override
public void run() {
mImgIv.setImageBitmap(bitmap);
}
});
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
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 java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import javax.net.ssl.HandshakeCompletedListener;
public class HttpActivity extends AppCompatActivity {
private final String IMG_URL = "http://img4.imgtn.bdimg.com/it/u=1968856895,1816029947&fm=26&gp=0.jpg";
private final int SUCCESS = 0;
private final int FAIL = -1;
private String response_msg = "";
private final String GETURL = "http://v.juhe.cn/toutiao/index?type=top&&key=22a108244dbb8d1f49967cd74a0c144d";
private final String POSTURL = "http://v.juhe.cn/toutiao/index";
private ImageView mImgIv;
Handler mHttpClientHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
int what = msg.what;
switch (what) {
case SUCCESS:
String result = (String) msg.obj;
Toast.makeText(HttpActivity.this, result, Toast.LENGTH_SHORT).show();
parseData(result);
break;
case FAIL:
Toast.makeText(HttpActivity.this, response_msg, Toast.LENGTH_SHORT).show();
break;
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_http);
initView();
}
private void initView() {
mImgIv = (ImageView) findViewById(R.id.iv_img);
}
/**
* 解析返回的json字符串
*
* @param result
*/
private void parseData(String result) {
// TODO: 2017/8/7 同学们实现
}
/**
* get请求
*
* @param v
*/
public void getClick(View v) {
//开启子线程,处理get请求
new Thread(new Runnable() {
@Override
public void run() {
getNews();
}
}).start();
}
/**
* post请求
*
* @param v
*/
public void postClick(View v) {
//开启子线程,处理post请求
new Thread(new Runnable() {
@Override
public void run() {
postNews("top", "22a108244dbb8d1f49967cd74a0c144d");
}
}).start();
}
/**
* 下载图片
* @param v
*/
public void imgClick(View v){
//开启子线程,处理post请求
new Thread(new Runnable() {
@Override
public void run() {
downloadImg();
}
}).start();
}
/**
* get请求获取新闻数据
*/
private void getNews() {
StringBuffer result = new StringBuffer();
//创建HttpClient对象,打开一个浏览器
HttpClient httpClient = new DefaultHttpClient();
//创建HttpGet对象,get请求的对象,传入url
HttpGet httpGet = new HttpGet(GETURL);
try {
//发起请求,拿到HttpResponse对象,这个对象是服务器返回的数据对象
HttpResponse httpResponse = httpClient.execute(httpGet);
//根据响应行,拿到响应吗
int responseCode = httpResponse.getStatusLine().getStatusCode();
response_msg = httpResponse.getStatusLine().getReasonPhrase();
if (200 == responseCode) {//如果响应码是200,则请求成功,否则失败
//得到返回的实体对象
HttpEntity entity = httpResponse.getEntity();
InputStream in = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line = null;
while ((line = reader.readLine()) != null) {
result.append(line);
}
Log.d("result--------", result.toString());
Message msg = new Message();
msg.what = SUCCESS;
msg.obj = result.toString();
mHttpClientHandler.sendMessage(msg);
} else {//请求失败,处理请求失败逻辑
Message msg = new Message();
msg.what = FAIL;
mHttpClientHandler.sendMessage(msg);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
httpClient.getConnectionManager().shutdown();
}
}
/**
* post请求
*/
private void postNews(String type, String key) {
String result = null;
HttpClient client = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(POSTURL);
try {
//封装传递参数的集合
List<NameValuePair> parameters = new ArrayList<NameValuePair>();
//往这个集合中添加你要传递的参数
parameters.add(new BasicNameValuePair("type", type));
parameters.add(new BasicNameValuePair("key", key));
//创建传递参数封装 实体对象
UrlEncodedFormEntity encodeEntity = new UrlEncodedFormEntity(parameters, "UTF-8");//设置传递参数的编码
//把实体对象存入到httpPost对象中
httpPost.setEntity(encodeEntity);
//3. 调用第一步中创建好的实例的 execute 方法来执行第二步中创建好的 method 实例
HttpResponse response = client.execute(httpPost); //HttpUriRequest的后代对象 //在浏览器中敲一下回车
//根据响应行,拿到响应吗
int responseCode = response.getStatusLine().getStatusCode();
response_msg = response.getStatusLine().getReasonPhrase();
//4. 读 response
if (200 == responseCode) {//如果响应码是200,则请求成功,否则失败
//得到返回的实体对象
HttpEntity entity = response.getEntity();
InputStream in = entity.getContent();
ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
int length = 0;
byte[] buffer = new byte[1024];
while ((length = in.read(buffer)) != -1) {
byteOut.write(buffer, 0, length);
}
result = byteOut.toString("utf-8");
System.out.println("result=====" + result);
Message msg = new Message();
msg.what = SUCCESS;
msg.obj = result;
mHttpClientHandler.sendMessage(msg);
} else {//请求失败,处理请求失败逻辑
Message msg = new Message();
msg.what = FAIL;
mHttpClientHandler.sendMessage(msg);
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 图片下载
*/
private void downloadImg() {
try {
URL u = new URL(IMG_URL);
HttpURLConnection connection = (HttpURLConnection) u.openConnection();
connection.connect();
if (200 == connection.getResponseCode()) {
InputStream in = connection.getInputStream();
final Bitmap bitmap = BitmapFactory.decodeStream(in);
mImgIv.post(new Runnable() {
@Override
public void run() {
mImgIv.setImageBitmap(bitmap);
}
});
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
阅读全文
0 0
- HttpClient的GET和POST解析
- HttpClient 的Get和Post
- HttpClient的get和post
- httpclient的post和get,httpurlconnection的post和get
- HttpClient Get和Post
- httpclient的get和post请求
- Post和Get在HttpClient的使用
- HttpClient的Post和Get访问网页
- HttpClient的Post和Get方法
- HttpClient的get和post请求数据
- HttpClient 的post和get请求
- httpClient的Get和Post请求
- HttpClient的post和get请求
- Httpclient的Get请求和Post请求
- httpclient的get和post请求
- HttpClient的Get请求和Post请求
- HttpClient的GET和POST请求
- httpclient中get和post的区别
- “The left-hand side of an assignment must be a variable” problem with charAt
- jQuery datatables插件
- android O正式包即将发布,你准备好了吗
- UVA 11300 Spreading the Wealth
- 求大佬解释下ptrace的pt_regs的定义,而且分为i386 arm x86和aarch64的不同分支
- HttpClient的GET和POST解析
- mysql导出所有用户权限脚本
- 《数据库SQL实战》从titles表获取按照title进行分组
- 数据库系统原理
- HDU 3974 Assign the task——线段树
- 谷歌三大论文之一-Google File System
- HDU2859 Phalanx dp
- DeepLearning——随机梯度下降
- openwrt-mt7688 添加应用程序