[java]代码库
package com.example.day06_httpclient_post;
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.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import com.google.gson.Gson;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
public class MainActivity extends Activity {
String path = "http://v.juhe.cn/weixin/query";
//key=b3edac6e41f3f3c84b855019e47b7ace
Handler handler=new Handler(){
public void handleMessage(android.os.Message msg) {
Bean bean = (Bean) msg.obj;
listView.setAdapter(new ArrayAdapter<Info>(MainActivity.this, android.R.layout.simple_list_item_1, bean.result.list));
};
};
private ListView listView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.listView);
}
public void button(View v){
new Thread() {
public void run() {
getData();
};
}.start();
}
/**
* 请求数据
*/
protected void getData() {
HttpClient client=new DefaultHttpClient();
//通过posty方式请求,设置接口地址
HttpPost httpPost=new HttpPost(path);
//得到集合,用于添加参数
List<NameValuePair> list=new ArrayList<>();
//以键值对的形式设置传给服务器的参数
list.add(new BasicNameValuePair("key", "b3edac6e41f3f3c84b855019e47b7ace"));
try {
//得到实体, 设置要传递的参数, 设置编码
UrlEncodedFormEntity urlEncodedFormEntity=new UrlEncodedFormEntity(list, "utf-8");
//设置传递的实体
httpPost.setEntity(urlEncodedFormEntity);
//执行请求.得到返回数据
HttpResponse httpResponse = client.execute(httpPost);
//得到响应码
int statusCode = httpResponse.getStatusLine().getStatusCode();
//响应码等于200,请求成功,取出服务器响应的数据
if(statusCode==200){
//得到实体
HttpEntity entity = httpResponse.getEntity();
//实体转成字符串
String string = EntityUtils.toString(entity);
Log.d("logd", ""+string);
////////////////////////////////////////////////////////////////
Gson gson=new Gson();
Bean bean = gson.fromJson(string, Bean.class);
Message msg=Message.obtain();
msg.obj=bean;
handler.sendMessage(msg);
}else{
Toast.makeText(this, " 网络异常 ", 1).show();
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
初级程序员
by: amosyhpz 发表于:2017-03-08 21:32:44 顶(0) | 踩(0) 回复
是安卓客户端的代码?
回复评论