2016-10-04 64 views
-2

這就是我在iOS中調用web服務的方式。在Android中使用httpheaders和參數在iOS中調用webservice

let request = NSMutableURLRequest(URL: NSURL(string: "reqesturl")!) 
    let session = NSURLSession.sharedSession() 

    request.HTTPMethod = "POST" 

    let params = ["key1": value1, "key2": value2, "key3": value3, "key4": value4] as Dictionary<String, AnyObject> 

    request.HTTPBody = try! NSJSONSerialization.dataWithJSONObject(params, options: .PrettyPrinted) 

    request.addValue("application/json", forHTTPHeaderField: "Content-Type") 

    request.addValue("application/json", forHTTPHeaderField: "Accept") 

    request.addValue(SESSION_ID!, forHTTPHeaderField: "sSessionId") 

    let task = session.dataTaskWithRequest(request) {(data, response, error) in 
     dispatch_async(dispatch_get_main_queue(), { 
      if response != nil { 
       let httpResponse = response as? NSHTTPURLResponse 
       let status = httpResponse!.allHeaderFields["internalErrors"] as? String 
       self.statusCode = Int(status!) 

       if self.statusCode != nil { 
        if self.statusCode > 0 && self.statusCode < ERRORCODE.count { 
         if self.statusCode == 8 { 
          APPDELEGATE?.showErrorCode(self.statusCode) 
         } 
         postCompleted(Succeeded: false , CheckinDetails: "Failed") 

        } 
       }else { 
        APPDELEGATE?.showErrorCode(78) 
       } 

      }else { 
       postCompleted(Succeeded: false , CheckinDetails: "Failed") 
      } 
     }) 
    } 
    task.resume() 

我該如何在Android中實現這一目標?我正在嘗試將Http標頭字段添加到Web請求中。然後我爲這個請求添加參數。我是android開發新手。

+0

你應該看看HttpUrlConnection類。這裏從android開發人員培訓https://developer.android.com/training/basics/network-ops/connecting.html#download一個小解釋。要添加請求標頭,請使用setRequestProperty方法 – MatPag

回答

0

這可能是您的使用案例的完整解決方案。顯然你需要一個合適的方式來獲得JSON。我建議你使用Jackson或GSON庫來管理JSON對象和字符串。

public String httpPOSTrequest(String url, String json) { 

    //if request will success, the server response will be saved here 
    String response = ""; 

    try { 

     URL urll = new URL(url); 
     HttpsURLConnection conn = (HttpsURLConnection) urll.openConnection(); 
     conn.setReadTimeout(10000); 
     conn.setConnectTimeout(15000); 
     conn.setRequestMethod("POST"); 
     conn.setRequestProperty("Content-Type", "application/json"); 
     conn.setRequestProperty("Accept", "application/json"); 
     conn.setDoInput(true); 
     conn.setDoOutput(true); 


     OutputStream os = conn.getOutputStream(); 
     BufferedWriter writer = new BufferedWriter(
       new OutputStreamWriter(os, "UTF-8")); 
     writer.write(json); 
     writer.flush(); 
     writer.close(); 
     os.close(); 

     conn.connect(); //real call starts here 

     int responseCode = conn.getResponseCode() 

     if (responseCode == HttpsURLConnection.HTTP_OK) { 
      String line; 
      BufferedReader br = new BufferedReader(
        new InputStreamReader(conn.getInputStream())); 
      while ((line=br.readLine()) != null) { 
        response+=line; 
      } 
     } 
    } catch (Exception e { 
     e.printStackTrace(); 
    } 

    return response; 
} 

此外,這段代碼需要更好的錯誤處理,但我認爲這可能是一個很好的起點。

相關問題