1. 程式人生 > >Android使用Post方法獲取Json配置

Android使用Post方法獲取Json配置

1. 首先是使用Post方法從網路獲取Json的程式碼, 返回型別為String:

public  String SendPostRequest(String param_key, String param_val){
        HttpURLConnection conn=null;
        String backcontent="";
        try { 
	    String str_url="http://www.forexample.com/"; 
	    URL url = new URL(str_url); 
	    conn = (HttpURLConnection) url.openConnection(); 
	
conn.setRequestMethod("POST");  //conn.setRequestProperty("Content-Type", "application/json");  conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");  conn.setConnectTimeout(1000);  DataOutputStream outputStream=new DataOutputStream(conn.getOutputStream()); 
String param=param_key + "=" + URLEncoder.encode(param_val,"UTF-8");  outputStream.writeBytes(param);  outputStream.flush(); outputStream.close();  if(HttpURLConnection.HTTP_OK==conn.getResponseCode()){     Log.i("POST","post sucess");     StringBuffer sb=new StringBuffer(); 
String readLine=new String();  BufferedReader responseReader=new BufferedReader(new InputStreamReader(conn.getInputStream(),"UTF-8"));  while((readLine=responseReader.readLine())!=null){     sb.append(readLine).append("\n");  backcontent= sb.toString();  backcontent=URLDecoder.decode(backcontent,"UTF-8");  Log.i("Post","post content" + backcontent);  responseReader.close();     }else {     Log.i("POST","post failed");  } catch (Exception e) {     e.printStackTrace();  } finally {     conn.disconnect();  return backcontent;  }

2. 呼叫方式,我是直接放在了onCreate方法中,需要注意的是StrictMode的兩行程式碼,如果不賦予許可權可能訪問失敗:

  StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
  StrictMode.setThreadPolicy(policy);
  String response_content = SendPostRequest("client_platform", "Android");

3. 後面的可以對response_content進行解析獲取json的格式的配置資訊,在最後貼一下可能用到的依賴包。

import android.os.Bundle;
import android.widget.TextView;
import android.content.Intent;
import android.net.Uri;
import android.os.StrictMode;

import java.io.InputStream;
import java.lang.reflect.Method;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import android.util.Log;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.DataOutputStream;
import java.io.BufferedReader;
import org.json.JSONArray;
import org.json.JSONObject;
import java.io.BufferedInputStream;
import java.io.FileOutputStream;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.io.InputStreamReader;
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.content.Context;