android {
useLibrary 'org.apache.http.legacy'
}
public class MainActivity extends AppCompatActivity {
@Override
protected voidonCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public voidbtnForGet(View view){
new Thread(){
@Override
publicvoid run() {
httpClientForGet();
}
}.start();
}
public voidbtnForPost(View view){
new Thread(){
@Override
publicvoid run() {
httpClientForPost("52cb54f14bc3bbcd9a96e1d13ee0cf2b");
}
}.start();
}
private voidhttpClientForGet(){
try {
//打开浏览器
HttpClienthttpClient = new DefaultHttpClient();
//填一下地址
HttpGethttpGet = newHttpGet("http://japi.juhe.cn/health_knowledge/categoryList?key=eb033dfcf95c03f9f451f6973049e6be");
//敲回车,并等待服务器响应
HttpResponse httpResponse = httpClient.execute(httpGet);
//getStatusLine() 得到状态行 getStatusCode()得到状态码
int code =httpResponse.getStatusLine().getStatusCode();
if(code ==200){
//getEntity() 得到响应实体
InputStream is =httpResponse.getEntity().getContent();
//字节流转字符串
String result =StreamTools.readFromNetWork(is);
System.out.println("HttpClientGet结果 : "+result);
}
} catch (Exception e) {
e.printStackTrace();
}
}
private voidhttpClientForPost(String key){
try {
//1.打开浏览器
HttpClienthttpClient = new DefaultHttpClient();
//2.填一下地址
HttpPosthttpPost = newHttpPost("http://v.juhe.cn/expressonline/getCarriers.php");
//设置请求参数
Listparams = new ArrayList();
//往集合添加请求参数
params.add(new BasicNameValuePair("key",key));
params.add(new BasicNameValuePair("ex_category","顺丰"));
//params.add(new BasicNameValuePair())
httpPost.setEntity(new UrlEncodedFormEntity(params));
//3.敲回车,等待服务器响应
HttpResponse httpResponse = httpClient.execute(httpPost);
//4.得到服务器响应状态码
int code =httpResponse.getStatusLine().getStatusCode();
if(code ==200){//判断服务器是否成功响应
//得到服务器的响应内容
InputStream is =httpResponse.getEntity().getContent();
String result =StreamTools.readFromNetWork(is);
System.out.println("结果 -->"+result);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}