2016-01-27 38 views
0

我正在從API響應,當我從郵差提交請求等所示的圖像中從Android的我想要調用與POST方法API

screenshot1.jpg =我需要通過 screenshot2.jpg數據=的結果我們得到

screenshot1.jpg screenshot2.jpg

我試着打電話給他們通過與下面的代碼的Android,但它不工作,

JSONObject login = new JSONObject(); 
login.put("username", userName); 
login.put("password", password); 
login.put("platform", "ANDROID"); 
login.put("location", "56.1603092,10.2177147"); 

String str = WebServices.excutePost(url, login); 


public static String excutePost(String targetURL, JSONObject urlParameters) { 
    URL url; 
    HttpURLConnection connection = null; 
    try { 


     //Create connection 
     url = new URL(targetURL); 
     connection = (HttpURLConnection) url.openConnection(); 
     connection.setRequestMethod("POST"); 
     connection.setRequestProperty("Content-Type", 
       "application/raw"); 

     connection.setRequestProperty("Content-Length", "" + 
       Integer.toString(urlParameters.toString().getBytes().length)); 
     connection.setRequestProperty("Content-Language", "en-US"); 


     connection.setUseCaches(false); 
     connection.setDoInput(true); 
     connection.setDoOutput(true); 


     //Send request 

     OutputStream out = new BufferedOutputStream(connection.getOutputStream()); 
     BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out, "UTF-8")); 
     writer.write(String.valueOf(urlParameters.toString().getBytes("UTF-8"))); 
     out.close(); 
     //connection.disconnect(); 

     //Get Response 
     InputStream is = connection.getInputStream(); 
     BufferedReader rd = new BufferedReader(new InputStreamReader(is)); 
     String line; 
     StringBuffer response = new StringBuffer(); 
     while ((line = rd.readLine()) != null) { 
      response.append(line); 
      response.append('\r'); 
     } 
     rd.close(); 
     return response.toString(); 

    } catch (Exception e) { 

     e.printStackTrace(); 
     return null; 

    } finally { 

     if (connection != null) { 
      connection.disconnect(); 
     } 
    } 
} 
+2

你能說說'不行'嗎?它在做什麼或不做什麼?是否有錯誤訊息? – Breavyn

+0

我認爲你的內容類型應該是應用程序/ json –

+0

如果可能,你可以提供堆棧跟蹤問題嗎? –

回答

1

您可以使用以下方法:

public String executePost(String targetURL,String urlParameters) { 
    int timeout=5000; 
    URL url; 
    HttpURLConnection connection = null; 
    try { 
     // Create connection 

     url = new URL(targetURL); 
     connection = (HttpURLConnection) url.openConnection(); 
     connection.setRequestMethod("POST"); 
     connection.setRequestProperty("Content-Type", 
       "application/json"); 

     connection.setRequestProperty("Content-Length", 
       "" + Integer.toString(urlParameters.getBytes().length)); 
     connection.setRequestProperty("Content-Language", "en-US"); 

     connection.setUseCaches(false); 
     connection.setDoInput(true); 
     connection.setDoOutput(true); 
     connection.setConnectTimeout(timeout); 
     connection.setReadTimeout(timeout); 

     // Send request 
     DataOutputStream wr = new DataOutputStream(
       connection.getOutputStream()); 
     wr.writeBytes(urlParameters); 
     wr.flush(); 
     wr.close(); 

     // Get Response 
     InputStream is = connection.getInputStream(); 
     BufferedReader rd = new BufferedReader(new InputStreamReader(is)); 
     String line; 
     StringBuffer response = new StringBuffer(); 
     while ((line = rd.readLine()) != null) { 
      response.append(line); 
      response.append('\r'); 
     } 
     rd.close(); 
     return response.toString(); 

    } catch (SocketTimeoutException ex) { 
     ex.printStackTrace(); 

    } catch (MalformedURLException ex) { 
     Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex); 
    } catch (UnknownHostException e) { 
     e.printStackTrace(); 
    } catch (IOException ex) { 

     Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex); 
    } catch (Exception e) { 
     e.printStackTrace(); 
    } finally { 

     if (connection != null) { 
      connection.disconnect(); 
     } 
    } 
    return null; 
} 

您可以創建URL參數,如:

JSONObject loginParams = new JSONObject(); 
loginParams .put("username", userName); 
loginParams .put("password", password); 
loginParams .put("platform", "ANDROID"); 
loginParams .put("location", "56.1603092,10.2177147"); 

調用方法,如:

executePost(serviceURL,loginParams.toString()); 
0

可以使用retrofit庫更容易實現與REST服務進行網絡通信。

順便說一句,你可以試試我的解決方案爲您的問題:

  • 首先,創建一個executeHttp方法

     private JSONObject executeHttp(HttpUriRequest request, Context context) throws ClientProtocolException, IOException { 
         HttpParams httpParameters = new BasicHttpParams(); 
          // Set the timeout in milliseconds until a connection is established. 
          // The default value is zero, that means the timeout is not used. 
          int timeoutConnection = 3000; 
          HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection); 
          // Set the default socket timeout (SO_TIMEOUT) 
          // in milliseconds which is the timeout for waiting for data. 
          int timeoutSocket = 10000; 
          HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket); 
    
          DefaultHttpClient client = new DefaultHttpClient(httpParameters); 
          // add your header in here - I saw your header has 7 params 
          request.addHeader("Authorization", getToken()); 
          request.addHeader("APIKey", API_KEY); 
          request.addHeader("Content-Type", "application/x-www-form-urlencoded"); 
          request.addHeader("X-Request-Mime-Type", "application/json;"); 
          HttpResponse execute = client.execute(request); 
          InputStream content = execute.getEntity().getContent(); 
          // implement your handle response here, below is just an example 
          try { 
           return new JSONObject().put("content", this.convertStreamToByteArray(content)); 
          } catch (JSONException e) { 
          //Crashlytics.logException(e); 
           Log.e(LOG_TAG, "Error converting stream to byte array: " + e.getMessage()); 
           return new JSONObject(); 
    
          } 
         } 
    

然後創建一個方法來處理POST請求

public JSONObject doPost(List<NameValuePair> headerParams, List<NameValuePair> parameters, String url, Context context) throws ClientProtocolException, IOException { 
     HttpPost httpPost = new HttpPost(url); 
     // add the header if needed 
     if (headerParams != null) { 
      for (NameValuePair headerParam: headerParams) { 
       httpPost.addHeader(headerParam.getName(), headerParam.getValue()); 
      } 
     } 
     httpPost.setEntity(new UrlEncodedFormEntity(parameters, "UTF-8")); 

     return executeHttp(httpPost, context); 
    } 

最後,調用剛剛創建的api。

JSONObject json = doPost(header, nameValuePairs, yourUrl, context); 

與namevaluepairs中被

  List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); 
      nameValuePairs.add(new BasicNameValuePair("username", userName)); 
      nameValuePairs.add(new BasicNameValuePair("password", password)); 
      nameValuePairs.add(new BasicNameValuePair("platform", "ANDROID")); 
      nameValuePairs.add(new BasicNameValuePair("location", "56.1603092,10.2177147")); 
0

問題創建使用StringBuffer類,我使用的字符串得到響應,並將其完美地工作。感謝您的每一個人的意見和答案。