public class MainActivity extends AppCompatActivity {
@Override
protected void
onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void
btnForGet(View view){
new Thread(){
@Override
public
void run() {
httpClientForGet();
}
}.start();
}
public void
btnForPost(View view){
new Thread(){
@Override
public
void run() {
httpClientForPost("52cb54f14bc3bbcd9a96e1d13ee0cf2b");
}
}.start();
}
private void
httpClientForGet(){
try {
//打开浏览器
HttpClient
httpClient = new DefaultHttpClient();
//填一下地址
HttpGet
httpGet = new
HttpGet("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 void
httpClientForPost(String key){
try {
//1.打开浏览器
HttpClient
httpClient = new DefaultHttpClient();
//2.填一下地址
HttpPost
httpPost = new
HttpPost("http://v.juhe.cn/expressonline/getCarriers.php");
//设置请求参数
List
params = 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();
}
}
}