2014-09-24 62 views
2

我想調用這個Web服務,但它的反應是空如何調用JSON webservice?

<script type="text/javascript"> 
    jQuery(document).ready(function(){ 
     var user = {nick :"rajesh", password:"123456", device_id:"123456677"}; 
     jQuery.ajax({ 
      type: "post", 
      data :JSON.stringify(user), 
      url: "http://localhost:81/sazpin/user/users/index.json", 
      contentType: "application/json; charset=utf-8", 
      dataType: "json", 
      success: function(data) { 
       console.log(data); 
      } 
     }); 
    }); 
</script> 

我httppost客戶端是

HttpClient httpClient = new DefaultHttpClient(); 

// post header 
HttpPost httpPost = new HttpPost(url);     
httpPost.setEntity(se);   
httpPost.setHeader("Accept", "application/json"); 
httpPost.setHeader("Content-type", "application/json"); 

請有人幫助我如何調用這個Web服務,並得到響應?

+1

讀取響應數據如何是一個Web服務?我看到的只是一個JavaScript腳本。 HttpClient不會調用javascript – 2014-09-24 11:30:12

+0

請告訴我如何調用這個 – 2014-09-24 11:43:29

回答

1

試試看看這個代碼。首先創建你的AsyncTask。

public class ResquestJSON extends AsyncTask<String, Void, String>{ 
JSONObject jsonObject = new JSONObject(); 
String response; 

protected String doInBackground(String... params){ 
    HttpPost httpPost = new HttpPost("http://192.168.10.101:8090/download");//your webservice url here 
    HttpClient httpClient = new DefaultHttpClient(); 
    HttpContext httpContext = new BasicHttpContext(); 
    try { 
     jsonObject.put("firstParam", params[0]); 
     jsonObject.put("secondParam", params[1]); 

     StringEntity se = new StringEntity(jsonObject.toString()); 
     httpPost.addHeader("Content_Type", "application/json"); 
     httpPost.setEntity(se); 
     HttpResponse httpResponse = httpClient.execute(httpPost, httpContext); 

     HttpEntity entity = httpResponse.getEntity(); 

     if (entity!=null){ 
      response = EntityUtils.toString(entity); 
      entity.consumeContent(); 
      httpClient.getConnectionManager().shutdown(); 
     } 
    } catch (JSONException|IOException|IllegalArgumentException e) { 
     return UtilityConstants.ERROR; 
    } 
    return response; 
} 

現在從您的活動中調用此類AsyncTask方法。

String response = new ResquestJSON().execute(firstParam, secondParam).get(); 
JSONObject obj = new JSONObject(response); 
String nick = obj.getString("nick"); 
String password = obj.getString("password"); 
String deviceId = obj.getString("deviceId"); 

希望它可以幫助你。

0
URL url = new URL("http://www.example.com/"); 
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); 
try { 
    urlConnection.setDoOutput(true); 
    urlConnection.setChunkedStreamingMode(0); 

    OutputStream out = new BufferedOutputStream(urlConnection.getOutputStream()); 
    writeStream(out); 

    InputStream in = new BufferedInputStream(urlConnection.getInputStream()); 
    readStream(in); 
} finally { 
    urlConnection.disconnect(); 
} 

實現方法writeStream寫的內容作爲POST數據,並readStream從服務器