2016-04-19 52 views
-1

我是新的,並試圖發送JSON請求到Web服務器,並嘗試使用HttpURLConnection類獲得JSON響應,但它給人的HTTP 402狀態,我沒有得到任何解決方案的任何高級請大家幫忙,我的代碼如下如何在web服務器上使用HttpUrlConnection在Android上發佈json請求?

URL url_webServer = new URL("http://teespire.com/ptracking/post/index.php?tag=GetTrackerInfo"); 

urlConnection = (HttpURLConnection) url_webServer.openConnection(); 
urlConnection.setRequestMethod("POST"); 
urlConnection.setDoOutput(true); 
urlConnection.setDoInput(true); 
//urlConnection.setDoInput(true); 
//11urlConnection.connect(); 
urlConnection.setRequestProperty("Content-Type", "application/json"); 
urlConnection.setRequestProperty("Accept", "application/json"); 
urlConnection.connect(); 

JSONObject jsonObject_webJsonRequest = new JSONObject(); 
jsonObject_webJsonRequest.put("tid", "1"); 

outputStreamWriter = new OutputStreamWriter(urlConnection.getOutputStream()); 
outputStreamWriter.write((jsonObject_webJsonRequest.toString())); 

//jsonObject_webJsonRequest.toString().getBytes(); 
//outputStreamWriter.write(jsonObject_webJsonRequest.toString().getBytes()); 

//clean up 
outputStreamWriter.flush(); 
outputStreamWriter.close(); 

StringBuilder stringBuilder = new StringBuilder(); 

int HttpResult = urlConnection.getResponseCode(); 

if (HttpResult == HttpURLConnection.HTTP_OK) { 

    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), "utf-8")); 

    String line = null; 

    while ((line = bufferedReader.readLine()) != null) { 
     stringBuilder.append(line).append("\n"); 
    } 

    bufferedReader.close(); 

    String response = stringBuilder.toString(); 
} else { 
    String response = urlConnection.getResponseMessage(); 
}I am new and trying to send json request to web server and trying to get json response using httpUrlConnection but its giving http 402 status, i am failing to get any solution any senior please help, my code is as follow 

URL url_webServer = new URL("http://teespire.com/ptracking/post/index.php?tag=GetTrackerInfo"); 

urlConnection = (HttpURLConnection) url_webServer.openConnection(); 
urlConnection.setRequestMethod("POST"); 
urlConnection.setDoOutput(true); 
urlConnection.setDoInput(true); 
//urlConnection.setDoInput(true); 
//11urlConnection.connect(); 
urlConnection.setRequestProperty("Content-Type", "application/json"); 
urlConnection.setRequestProperty("Accept", "application/json"); 
urlConnection.connect(); 

JSONObject jsonObject_webJsonRequest = new JSONObject(); 
jsonObject_webJsonRequest.put("tid", "1"); 

outputStreamWriter = new OutputStreamWriter(urlConnection.getOutputStream()); 
outputStreamWriter.write((jsonObject_webJsonRequest.toString())); 

//jsonObject_webJsonRequest.toString().getBytes(); 
//outputStreamWriter.write(jsonObject_webJsonRequest.toString().getBytes()); 

//clean up 
outputStreamWriter.flush(); 
outputStreamWriter.close(); 

StringBuilder stringBuilder = new StringBuilder(); 

int HttpResult = urlConnection.getResponseCode(); 

if (HttpResult == HttpURLConnection.HTTP_OK) { 

    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), "utf-8")); 

    String line = null; 

    while ((line = bufferedReader.readLine()) != null) { 
     stringBuilder.append(line).append("\n"); 
    } 

    bufferedReader.close(); 

    String response = stringBuilder.toString(); 
} else { 
    String response = urlConnection.getResponseMessage(); 
} 

回答

0

根據W3.org狀態代碼402意味着

PaymentRequired 402

到這個消息的參數給出炭的規範ging 方案可以接受。客戶端可以用合適的 ChargeTo頭重試該請求。

這可能意味着服務器在其上承載您的Web服務需要一些款項做

+0

我正在重做這個應用程序,它做工精細及其web API測試工具也工作正常 – ASIM

0

調用此方法

public void senddatatoserver() { 
    //function in the activity that corresponds to the layout button 
    JSONObject post_dict = new JSONObject(); 

    try { 
     post_dict.put("Key1", value1); 
    post_dict.put("Key2", value2); 
    post_dict.put("Key3", value3); 
     post_dict.put("Key4", value4); 

    } catch (JSONException e) { 
     e.printStackTrace(); 
    } 
    if (post_dict.length() > 0) { 
     new SendJsonDataToServer().execute(String.valueOf(post_dict)); 

    } 
} 

然後調用這樣

class SendJsonDataToServer extends AsyncTask<String, String, String> { 
     String JsonResponse = null; 
     ProgressDialog dialog; 

     @Override 
     protected void onPreExecute() { 
      super.onPreExecute(); 

      dialog = new ProgressDialog(TwoAnswerScreenActivity.this); 
      dialog.setMessage("Please Wait..."); 
      dialog.setCancelable(false); 
      dialog.show(); 


     } 


     @Override 
     protected String doInBackground(String... params) { 

      String JsonDATA = params[0]; 
      HttpURLConnection urlConnection = null; 
      BufferedReader reader = null; 
      try { 
       URL url = new URL("http://teespire.com/ptracking/post/index.php"); 
       urlConnection = (HttpURLConnection) url.openConnection(); 
       urlConnection.setDoOutput(true); 
       // is output buffer writter 
       urlConnection.setRequestMethod("POST"); 
       urlConnection.setRequestProperty("Content-Type", "application/json"); 
       urlConnection.setRequestProperty("Accept", "application/json"); 
//set headers and method 
       Writer writer = new BufferedWriter(new OutputStreamWriter(urlConnection.getOutputStream(), "UTF-8")); 
       writer.write(JsonDATA); 
// json data 
//    Log.e("Response", JsonResponse + ""); 
       writer.close(); 
       InputStream inputStream = urlConnection.getInputStream(); 
//input stream 
       StringBuffer buffer = new StringBuffer(); 
       if (inputStream == null) { 
        // Nothing to do. 
        return null; 
       } 
       reader = new BufferedReader(new InputStreamReader(inputStream)); 

       String inputLine; 
       while ((inputLine = reader.readLine()) != null) 
        buffer.append(inputLine + "\n"); 
       if (buffer.length() == 0) { 
        // Stream was empty. No point in parsing. 
        return null; 
       } 
       JsonResponse = buffer.toString(); 
       Log.e("Response", JsonResponse + ""); 
//response data 
       Log.i("Tag", JsonResponse); 
       //send to post execute 

       return JsonResponse; 
//    return null; 


      } catch (IOException e) { 
       e.printStackTrace(); 
      } finally { 
       if (urlConnection != null) { 
        urlConnection.disconnect(); 
       } 
       if (reader != null) { 
        try { 
         reader.close(); 
        } catch (final IOException e) { 
         Log.e("Tag", "Error closing stream", e); 
        } 
       } 
      } 
      return null; 
     } 


     @Override 
     protected void onPostExecute(String s) { 


      if (JsonResponse != null) { 
       dialog.dismiss(); 
       //Your success code 
      } 


     } 

    } 
0
的的AsyncTask

402狀態可能意味着服務收費且不免費,但不應使用,最常見的情況是意味着你已經超出了請求限制。 4xx Client Error - Wikipedia。但你可以嘗試這樣的事情。

HttpURLConnection connection = null; 

    // making HTTP request 
    try { 

     String req = URLEncoder.encode(jsonObject_webJsonRequest.toString(), "UTF-8"); 

     URL url = new URL("http://teespire.com/ptracking/post/index.php?tag=GetTrackerInfo"); 

     connection = (HttpURLConnection) url.openConnection(); 
     connection.setRequestMethod("POST"); // 
     connection.setDoOutput(true); 
     connection.setDoInput(true); 
     connection.setFixedLengthStreamingMode(req.getBytes().length); 
     connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8"); 
     PrintWriter out = new PrintWriter(connection.getOutputStream()); 
     out.print(req); 
     out.close(); 

     try { 
      // parsing the response 
      BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8")); 
      StringBuilder sb = new StringBuilder(); 
      String line = null; 
      while ((line = reader.readLine()) != null) { 
       // System.out.println(line); // optional 
       sb.append(line + "\n"); 
      } 

      string = sb.toString(); 

     } catch (Exception e) { 
      Log.e("Buffer Error", "Error converting result " + e.toString()); 

     } 

     connection.disconnect(); 
    } catch (UnsupportedEncodingException e) { 
     e.printStackTrace(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 

    //parse the response 
+0

我重做這個程序,它工作正常在iOS上,並在網頁API測試工具,它的工作的罰款。 – ASIM

相關問題