2014-05-21 79 views
3

我正在實現一個GDK應用程序,並且需要在我的應用程序中執行一些HTTP Post請求。我是否會像在android手機上一樣發送HTTP請求,或者有其他方式嗎? (我嘗試了我在手機上使用的代碼,它不適用於玻璃。)Glass中的HTTP請求GDK

感謝您的幫助提前。

+0

你可以提供一個樣本你如何做的代碼,以及你在嘗試時遇到了什麼錯誤? – Prisoner

回答

3

您可以在智能手機中發送任何發佈請求,但請確保您使用AsyncTask發出請求。

例如:

private class SendPostTask extends AsyncTask<Void, Void, Void> { 

    @Override 
    protected Void doInBackground(Void... params) { 
      // Make your request POST here. Example: 
      myRequestPost(); 
      return null; 
    } 

    protected void onPostExecute(Void result) { 
     // Do something when finished. 
    } 
} 

而且你可以調用的AsyncTask任何地方:

new SendPostTask().execute(); 

而且例如myRequestPost(的)可能是:

private int myRequestPost() { 

    int resultCode = 0; 

    String url = "http://your-url-here"; 

    HttpClient client = new DefaultHttpClient(); 
    HttpPost post = new HttpPost(url); 

    // add headers you want, example: 
    // post.setHeader("Authorization", "YOUR-TOKEN"); 

    List<NameValuePair> urlParameters = new ArrayList<NameValuePair>(); 
    nameValuePairs.add(new BasicNameValuePair("id", "111111")); 
    nameValuePairs.add(new BasicNameValuePair("otherField", "your-other-data")); 

    try { 
     post.setEntity(new UrlEncodedFormEntity(urlParameters)); 

     HttpResponse response = client.execute(post); 
     System.out.println("\nSending 'POST' request to URL : " + url); 
     System.out.println("Post parameters : " + post.getEntity()); 
     System.out.println("Response Code : " + 
            response.getStatusLine().getStatusCode()); 

     resultCode = response.getStatusLine().getStatusCode(); 

     BufferedReader rd = new BufferedReader(
         new InputStreamReader(response.getEntity().getContent())); 

     StringBuffer result = new StringBuffer(); 
     String line = ""; 
     while ((line = rd.readLine()) != null) { 
      result.append(line); 
     } 

     System.out.println(result.toString()); 
    } catch (Exception e) { 
     Log.e("POST", e.getMessage()); 
    } 

    return resultCode; 
}