首页 > 代码库 > android http json请求3种不同写法

android http json请求3种不同写法

第一种:

  public static String invoke() {
        String result = null;
        try {
             final String url = "http://192.168.1.104:180/";

            HttpPost httpPost = new HttpPost(url);
            DefaultHttpClient httpClient = new DefaultHttpClient();

            //基本身份验证
            BasicCredentialsProvider bcp = new BasicCredentialsProvider();
            String userName = "liudong";
            String password = "123";
            bcp.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(
                    userName, password));
            httpClient.setCredentialsProvider(bcp);

            HttpResponse httpResponse = httpClient.execute(httpPost);

            StringBuilder builder = new StringBuilder();
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    httpResponse.getEntity().getContent()));
            for (String s = reader.readLine(); s != null; s = reader.readLine()) {
                builder.append(s);
            }
            result = builder.toString();
            Log.d(TAG, "result is ( " + result + " )");
        } catch (Exception e) {
            Log.e(TAG, e.toString());
        }
        Log.d(TAG, "over");
        return result;
    }

第二种:

public static String SendRequest(String adress_Http, String strJson) {

  String returnLine = "";
  try {

   System.out.println("**************开始http通讯**************");
   System.out.println("**************调用的接口地址为**************" + adress_Http);
   System.out.println("**************请求发送的数据为**************" + strJson);
   URL my_url = new URL(adress_Http);
   HttpURLConnection connection = (HttpURLConnection) my_url.openConnection();
   connection.setDoOutput(true);

   connection.setDoInput(true);

   connection.setRequestMethod("POST");
   
   connection.setUseCaches(false);
   
   connection.setInstanceFollowRedirects(true);
   
   connection.setRequestProperty("Content-Type", "application/json");
   
   connection.connect();
   DataOutputStream out = new DataOutputStream(connection
     .getOutputStream());
   
   byte[] content = strJson.getBytes("utf-8");
   
   out.write(content, 0, content.length);
   out.flush();
   out.close(); // flush and close

   BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"));

   //StringBuilder builder = new StringBuilder();

   String line = "";

   System.out.println("Contents of post request start");

   while ((line = reader.readLine()) != null) {
    // line = new String(line.getBytes(), "utf-8");
    returnLine += line;
    
    System.out.println(line);
    
   }

   System.out.println("Contents of post request ends");
   
   reader.close();
   connection.disconnect();
   System.out.println("========返回的结果的为========" + returnLine);

  } catch (Exception e) {
   e.printStackTrace();
  }

  return returnLine;

 }

 

第三种:

protected DAOReturnObject doInBackground(JSONObject... jsonObjects) {
  DAOReturnObject returnObject;
  try {
   publishProgress("处理中...");
   String serverUrl = "http://130.251.10.195:8091";//MServerSettingInfoDAO.getInstance().getUrl();
   String url = serverUrl+"/customerLogin";
   HttpPost httpPost = new HttpPost(url);
   Log.i("URL", url);
   ByteArrayEntity arrayEntity = null;
   byte[] jsonByte = null;
   try {
    jsonByte = jsonObjects[0].toString().getBytes(DEFAULT_ENCODING);
    arrayEntity = new ByteArrayEntity(jsonByte); 
   } catch (UnsupportedEncodingException e) {
    e.printStackTrace();
    throw new Exception("数据打包出错!");
   }
   Log.d("M-Client", "request JSON:\n" + new String(jsonByte, DEFAULT_ENCODING ));
   httpPost.setEntity(arrayEntity);
   httpPost.setHeader("Accept", "application/json");
   httpPost.setHeader("Content-type", "application/x-www-form-urlencoded");
   HttpResponse httpResponse;
   byte[] responseByte;
   String responseStr;
   try {
    DefaultHttpClient httpclient = new DefaultHttpClient();
    // 设置COOKIES
    HttpContext localContext = new BasicHttpContext();
    httpResponse = httpclient.execute(httpPost, localContext);
    if (httpResponse.getStatusLine().getStatusCode() != 200) {
     throw new Exception("接收数据出错:" + httpResponse.getStatusLine().toString());
    }
    responseByte = EntityUtils.toByteArray(httpResponse.getEntity());
    //写缓存
//    MServerSettingInfoDAO.getInstance().setStreamInfo(MClientFunction.getFileDir(), 
//      responseByte.length, "res");
//    MClientFunction.setResCurrentStream(responseByte.length);
    
    Log.d("M-Client", "response JSON:\n" + new String(responseByte, 0, responseByte.length, DEFAULT_ENCODING));
    responseStr = new String(responseByte, 0, responseByte.length, DEFAULT_ENCODING);
   } catch (ClientProtocolException e) {
    Log.e("M-Client", "接收数据出错!", e);
    throw new Exception("接收数据出错:" + e.getMessage(), e);
   } catch (IOException e) {
    Log.e("M-Client", "接收数据出错!", e);
    throw new Exception("接收数据出错:" + e.getMessage(), e);
   }
   try {
    Map<String, Object> responseMap = (Map<String, Object>)JsonUtil.json2Object(new JSONObject(responseStr));
    returnObject = new DAOReturnObject(Integer.parseInt((String) responseMap.get("code")), (String) responseMap.get("msg"), responseMap.get("res"));
   } catch (JSONException e) {
    Log.e("M-Client", "接收数据出错!", e);
    throw new Exception("接收数据出错:" + e.getMessage(), e);
   }
  } catch (Exception e) {
   return new DAOReturnObject(99, e.getMessage(), null);
  }
  return returnObject;
 }

 

记得加上访问权限:<uses-permission android:name="android.permission.INTERNET" />

android http json请求3种不同写法