如何在android中使用HttpUrlConnection在Web服务器上发布json请求?

时间:2016-04-19 09:37:50

标签: android json

我是新手并尝试将json请求发送到Web服务器并尝试使用httpUrlConnection获取json响应,但是它给出了http 402状态,我无法获得任何高级解决方案请帮助,我的代码如下

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();
}

3 个答案:

答案 0 :(得分:0)

根据W3.org 状态代码402表示

  

PaymentRequired 402

     

此消息的参数给出了充电规范   方案可以接受客户端可以使用合适的方式重试请求   ChargeTo标题。

这可能意味着您托管网络服务的服务器需要付款才能完成

答案 1 :(得分: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));

    }
}

然后像这样调用asynctask

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
            }


        }

    }

答案 2 :(得分:0)

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 
相关问题