android發送json並解析返回json

來源:互聯網
上載者:User

package com.http.test;


import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;


import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
//import android.widget.EditText;
import android.widget.TextView;


public class Http_testActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);


final TextView tv = (TextView) findViewById(R.id.result);
//final EditText ed = (EditText) findViewById(R.id.sendurl);
Button bt = (Button) findViewById(R.id.send);


bt.setOnClickListener(new OnClickListener() {// 建立第一個單擊事件


public void onClick(View v) {

String strResult = null;


try {
String httpUrl = "http://10.10.10.10:61002/userMessage/cJobConsultationUnread.json?data=688656&client_id=20012&view_id=268800";
// HttpGet連線物件
HttpGet httpRequest = new HttpGet(httpUrl);
// 取得HttpClient對象
HttpClient httpclient = new DefaultHttpClient();
// 請求HttpClient,取得HttpResponse
HttpResponse httpResponse = httpclient.execute(httpRequest);
// 請求成功
if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
// 取得返回的字串
strResult = EntityUtils.toString(httpResponse
.getEntity());
tv.setText(strResult);
} else {
tv.setText("請求錯誤!");
}


} catch (Exception e) {


}

//返回的json串strResult={"status":0,"message":"OK","data":15}
try { 
 
   JSONTokener jsonParser = new JSONTokener(strResult); 
   JSONObject js = (JSONObject) jsonParser.nextValue(); 
   // 接下來的就是JSON對象的操作了 
   System.out.println("status的值是:"+js.getString("status")); 
   System.out.println("message的值是:"+js.getString("message")); 
   System.out.println("data的值是:"+js.getInt("data"));
  
} catch (JSONException ex) { 
   // 異常處理代碼 
} 


}


});


}
}

 


摘自 移動互聯效能、android自動化、web自動化測試專欄

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.