使用client需要在build.gradle中添加
useLibrary 'org.apache.http.legacy'
1.请求方法创建 new Thread(new Runnable() { @Override public void run() { postNews("top","c1885686ef47f19bcb45e39c4447e040"); } }).start(); 2.详细请求/** * post请求 */ private void postNews(String type,String key) { HttpClient client=new DefaultHttpClient(); HttpPost httpPost=new HttpPost(POSTURL); String result=null; try { //封装传递参数的集合 ArrayList<NameValuePair> nameValuePair=new ArrayList<>(); //往这个集合中添加你要传递的参数 nameValuePair.add(new BasicNameValuePair("type",type)); nameValuePair.add(new BasicNameValuePair("key",key)); //创建传递参数封装 UrlEncodedFormEntity entity=new UrlEncodedFormEntity(nameValuePair,"UTF-8"); //将实体对象传入HttpHost httpPost.setEntity(entity); //调用第一步中创建好的实例 HttpResponse httpResponse = client.execute(httpPost); //响应 int statusCode = httpResponse.getStatusLine().getStatusCode(); String reasonPhrase = httpResponse.getStatusLine().getReasonPhrase(); if(200==statusCode){ //得到返回的实体对象 HttpEntity httpEntity=httpResponse.getEntity(); InputStream inputStream=httpEntity.getContent(); ByteArrayOutputStream byteArrayOutputStream=new ByteArrayOutputStream(); int len=0; byte[] buffer=new byte[1024]; while((len=inputStream.read(buffer))!=-1){ byteArrayOutputStream.write(buffer,0,len); } result=byteArrayOutputStream.toString(); System.out.println(result); pauseData(result); } } catch (Exception e) { e.printStackTrace(); } } /** * get请求 */ private void getNews() { //接受字符串 StringBuffer result=new StringBuffer(); //创建httpclient对象 HttpClient client= new DefaultHttpClient(); HttpGet httpGet=new HttpGet(GETURL); try { //发起请求,拿到HttpResponse对象 HttpResponse httpResponse=client.execute(httpGet); //得到响应码,和响应消息 int statusCode = httpResponse.getStatusLine().getStatusCode(); String reasonPhrase = httpResponse.getStatusLine().getReasonPhrase(); if(200==statusCode){ //得到返回的实体类 HttpEntity entity = httpResponse.getEntity(); //得到实体内容 InputStream inputStream = entity.getContent(); BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(inputStream)); String line=null; while((line=bufferedReader.readLine())!=null){ result.append(line); } System.out.println(result.toString()); } } catch (Exception e) { e.printStackTrace(); } }