Android 向 Server 端發送 JSON 格式資料
/**
* 發送JSON
*
* @param url
* 發送位置
* @param name
* JSON名稱
* @param obj
* JSON內容
* @return
* @throws ClientProtocolException
* @throws IOException
*/
public String doPost(String url, String name, JSONObject obj)
throws ClientProtocolException, IOException {
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
.detectDiskReads().detectDiskWrites().detectNetwork()
.penaltyLog().build());
StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
.detectLeakedSqlLiteObjects().detectLeakedClosableObjects()
.penaltyLog().penaltyDeath().build());
//-----------------------------------------------------------------------------以上是Android 3.0在網路的存取上增強的限制
HttpParams params = new BasicHttpParams();
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(params, "UTF-8");
params.setBooleanParameter("http.protocol.expect-continue", false);
HttpClient httpClient = new DefaultHttpClient(params);
HttpPost httpPost = new HttpPost(url);
HttpParams httpParams = new BasicHttpParams();
List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>();
try {
nameValuePair.add(new BasicNameValuePair(name, obj.toString()));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));
httpPost.setParams(httpParams);
HttpResponse response = httpClient.execute(httpPost);
String temp = EntityUtils.toString(response.getEntity());
return temp;
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}