2017-06-30 31 views
1

我想調用一個WEB API並使用下面的代碼獲取JSON輸出。錯誤訪問使用POSTMAN運行良好的Web API

我用POSTMAN測試了這個,它工作正常。 POST請求中有兩個值和更多的值。

但是,當我嘗試使用Apache的HTTP客戶端來訪問相同的Web API,我得到以下輸出和錯誤:

Response Code : 200 
Result:{"errorCode":3000,"errorMessage":"Invalid request parameters"} 

代碼:

import java.io.BufferedReader; 
import java.io.IOException; 
import java.io.InputStreamReader; 
import java.util.ArrayList; 
import java.util.List; 

import java.util.logging.Level; 
import java.util.logging.Logger; 
import org.apache.http.HttpResponse; 
import org.apache.http.NameValuePair; 
import org.apache.http.client.HttpClient; 
import org.apache.http.client.entity.UrlEncodedFormEntity; 
import org.apache.http.client.methods.HttpPost; 
import org.apache.http.impl.client.HttpClientBuilder; 
import org.apache.http.message.BasicNameValuePair; 


public class WhiteSourceAPI { 

public static void main(String[] args) { 

    try { 
     String url = "https://example.com/api"; 

     HttpClient client = HttpClientBuilder.create().build(); 
     HttpPost post = new HttpPost(url); 

     //header 
     post.setHeader("Content-Type", "application/json"); 
     post.setHeader("Accept-Charset", "UTF-8"); 

     List<NameValuePair> urlParameters = new ArrayList<>(); 
     urlParameters.add(new BasicNameValuePair("requestType", "xxxx")); 
     urlParameters.add(new BasicNameValuePair("projectToken", "xxxx-xxxx-xxxx-xxxx")); 

     post.setEntity(new UrlEncodedFormEntity(urlParameters)); 

     HttpResponse response = client.execute(post); 
     System.out.println("Response Code : " + response.getStatusLine().getStatusCode()); 

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

     StringBuilder result = new StringBuilder(); 
     String line = ""; 
     while ((line = rd.readLine()) != null) { 
      result.append(line); 
     } 
     System.out.println("Result:" +result); 
    } catch (IOException ex) { 
     Logger.getLogger(WhiteSourceAPI.class.getName()).log(Level.SEVERE, null, ex); 
    } 
} 
} 
+0

什麼是你的網絡API的參數? – ELITE

+3

您將Content-Type設置爲「application/json」,然後將UrlEncodedFormEntity作爲正文傳遞 - 這不是JSON。嘗試通過原始JSON來檢查這是否適用於您 – VitalyZ

+0

@VitalyZ謝謝,使用原始JSON而不是UrlEncodedFormEntity身體的工作。 – wishman

回答

0

正如@VitalyZ提到,我不應該使用UrlEncodedFormEntity作爲正文,而是使用原始JSON。

  JSONObject json = new JSONObject(); 
      json.put("requestType", "xxxx"); 
      json.put("projectToken", "xxxxxxxxxxxxxx"); 
      StringEntity params = new StringEntity(json.toString()); 
      post.setEntity(params); 
相關問題