2016-05-30 197 views
0

我正在創建用於詢問/回答問題的應用程序。 我在提問時遇到POST請求問題。無法在Java中發送正確的POST請求(Android Studio)

我試着使用像這樣在終端

curl -H "Content-Type: application/json" -d '{"firstName":"Chris", "lastName": "Chang", "email": "[email protected]"}' http://your-app-name.herokuapp.com/contacts 

和它的工作好。

但是,當我嘗試在AndroidStudio中發送POST請求時,我的參數(例如名稱,姓氏,電子郵件等)將不會發送。 我試過用https://github.com/kevinsawicki/http-request。請求發送(我知道,因爲它顯示請求的日期),但沒有任何參數。

我的代碼應該改變什麼才能正常工作?

Map<String, String> data = new HashMap<String, String>(); 
data.put("firstName", "Gena"); 
data.put("lastName", "Bukin"); 
if (HttpRequest.post("https://safe-citadel-91138.herokuapp.com/questions").form(data).created()) 
System.out.println("User was created"); 
+0

信息是哈希映射不發送到服務器(或也許它發送了,但請求沒有被正確創建) –

+1

您是否嘗試使用Volley發送它? –

+0

如果你去[鏈接](https://safe-citadel-91138.herokuapp.com/questions),你可以看到,前3個請求是從終端發送的,其他的是從Java發送的 –

回答

0

我剛剛嘗試創建一個用戶,它工作。您可以刷新已共享的link以檢查創建的用戶。

這是我曾嘗試

String endPoint= "https://safe-citadel-91138.herokuapp.com/questions"; 
     try { 

      DefaultHttpClient httpClient = new DefaultHttpClient(); 
      HttpPost post = new HttpPost(endPoint); 
      post.addHeader("Content-Type", "application/json"); 
      JSONObject obj = new JSONObject(); 

      obj.put("firstName", "TESTF"); 
      obj.put("lastName", "TESTL"); 
      obj.put("email", "[email protected]"); 

      StringEntity entity = new StringEntity(obj.toString()); 
      post.setEntity(entity); 
      HttpResponse response = httpClient.execute(post); 
}catch (Exception e){ 

     } 

UPDATE

BTW我從this鏈接中使用JSON罐子

+0

非常感謝,它工作!順便說一下,android已經取消了對Apache HTTP客戶端的支持 –

+0

@ValentinaPakhomova很高興!幫助! – Raghavendra

0

基本上,您的curl請求以請求正文發送JSON格式的用戶數據。您的Java代碼嘗試將請求中的數據作爲表單數據發送,這些數據與服​​務器不同並且可能不被服務器接受。

您可能需要改變你的代碼以使用HttpRequest.send(...)方法,而不是form

JSONObject json = new JSONObject(); 
json.put("firstName", "Gena"); 
json.put("lastName", "Bukin"); 
json.put("email", "[email protected]"); 

HttpRequest 
    .post("https://safe-citadel-91138.herokuapp.com/questions") 
    .contentType("application/json") 
    .send(json.toString()); 

而且在curl您使用調用訪問不同的URL比Java片斷http://your-app-name.herokuapp.com/contacts VS https://safe-citadel-91138.herokuapp.com/questions也許你與錯誤的端點交談?

您可能需要查看一些Java到JSON映射庫(如gson),以便將Java對象轉換爲適當的JSON或使用Android的JSONObject類。

UPDATE

  • 添加鏈接GSON爲JSON映射
  • 更新程式碼使用JSONObject的JSON映射
0

試試這個希望它會工作

public JSONObject getJSONFromUrl(String url_, JSONObject jsonObject) { 

    try { 
     URLConnection urlConn; 
     DataOutputStream printout; 

     URL url = new URL(url_); 
     urlConn = url.openConnection(); 
     urlConn.setDoInput(true); 
     urlConn.setDoOutput(true); 
     urlConn.setConnectTimeout(30000); 
     urlConn.setReadTimeout(30000); 
     urlConn.setUseCaches(false); 
     urlConn.setRequestProperty("Content-Type", "application/json"); 
     urlConn.setRequestProperty("Accept", "application/json"); 

     urlConn.setRequestProperty("Authorization", "token"); // If Applicable 
     urlConn.connect(); 
     printout = new DataOutputStream(urlConn.getOutputStream()); 
     printout.writeBytes(jsonObject.toString()); 
     printout.flush(); 
     BufferedReader reader = new BufferedReader(new InputStreamReader(urlConn.getInputStream())); 

     StringBuilder sb = new StringBuilder(); 
     String line = null; 
     while ((line = reader.readLine()) != null) { 
      sb.append(line + "\n"); 
     } 
     printout.close(); 
     reader.close(); 
     json = sb.toString(); 
    } catch (SocketException e) { 
     e.printStackTrace(); 
    } catch (MalformedURLException e) { 
     e.printStackTrace(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
    try { 
     jObj = new JSONObject(json); 
    } catch (JSONException e) { 
     e.printStackTrace(); 
    } 
    Applog.e("response", jObj + ""); 
    return jObj; 

} 
0

試試這個...

Map<String, Object> params = new LinkedHashMap<>(); 
params.put("firstName", "Gena"); 
params.put("lastName", "Bukin"); 


JSONObject jsonObject = POST("https://safe-citadel-91138.herokuapp.com/questions", params); 
    /** 
     * Method allows to HTTP POST request to the server to send data to a specified resource 
     * @param serverURL URL of the API to be requested 
     * @param params parameter that are to be send in the "body" of the request Ex: parameter=value&amp;also=another 
     * returns response as a JSON object 
     */ 
     public JSONObject POST(String serverURL, Map<String, Object> params) { 
      JSONObject jsonObject = null; 
      try { 
       URL url = new URL(serverURL); 

       Log.e(TAG, params.toString()); 
       StringBuilder postData = new StringBuilder(); 

       for (Map.Entry<String, Object> param : params.entrySet()) { 
        if (postData.length() != 0) postData.append('&'); 
        postData.append(URLEncoder.encode(param.getKey(), "UTF-8")); 
        postData.append('='); 
        postData.append(URLEncoder.encode(String.valueOf(param.getValue()), "UTF-8")); 
       } 
       Log.e("POST", serverURL + ":" + params.toString()); 
       byte[] postDataBytes = postData.toString().getBytes("UTF-8"); 
       HttpURLConnection connection = (HttpURLConnection) url.openConnection(); 
       connection.setRequestProperty("Content-Type", "application/json"); 
       connection.setRequestProperty("Content-Length", String.valueOf(postDataBytes.length)); 
       connection.setRequestMethod("POST"); 
       connection.setConnectTimeout(5000); 
       connection.setUseCaches(false); 
       connection.setDoOutput(true); 
       connection.getOutputStream().write(postDataBytes); 
       connection.connect(); 

       int statusCode = connection.getResponseCode(); 
       if (statusCode == 200) { 
        sb = new StringBuilder(); 
        reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); 
        String line; 
        while ((line = reader.readLine()) != null) { 
         sb.append(line + "\n"); 
        } 
       } 
       jsonObject = new JSONObject(sb.toString()); 
      } catch (Exception e) { 
       //e.printStackTrace(); 
      } 
      return jsonObject; 
     }