HttpClient的post用法

new Thread(){

public void run() {
  try {
    String path="路径";

    HttpClient httpClient=new DefaultHttpClient();
    HttpPost httpPost=new HttpPost(path);

//HttpGet get=new HttpGet("http://japi.juhe.cn/joke/content/list.from?key=5a14f8130268ec2825691c35176812b1&page=2&pagesize=10&sort=asc&time=1418745237");

 


    List<NameValuePair> parameters=new ArrayList<NameValuePair>();

//请求的网址上的参数

//key是指参数的名称

//value是指该参数的值

//如:parameters.add(new BasicNameValuePair(“name”, "lisi"));


    parameters.add(new BasicNameValuePair(key, value));

    HttpEntity entity=new UrlEncodedFormEntity(parameters);
    httpPost.setEntity(entity);

    HttpResponse response = httpClient.execute(httpPost);
    int code=response.getStatusLine().getStatusCode();

    if(code==200){

      InputStream is = response.getEntity().getContent();
      ByteArrayOutputStream bos=new ByteArrayOutputStream();
      int len=0;
      byte[] by=new byte[1024];
      while((len=is.read(by))!=-1){
          bos.write(by,0,len);
      }
      String json=bos.toString();

      Gson gson=new Gson();
      Smile smile = gson.fromJson(json, Smile.class);
      List<Data> data1=smile.result.data;


      Message msg=Message.obtain();
      msg.obj=data1;
      handler.sendMessage(msg);
  }
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

posted @ 2016-04-14 15:31  投个硬币吧  阅读(284)  评论(0)    收藏  举报