告诉我如何发送 Json 请求

Tell me how to send the Json request

I am sending the json request code give the error Is there any way how to send the json request with authentication.this Code give the Error in filenotfound "http://api.seatseller.travel/blockTicket"
//st = json object

       StringBuilder sb = new StringBuilder();  
         JSONObject jsonParam = st;//JSON 
         HttpURLConnection request=null; 
        OAuthConsumer consumer = new DefaultOAuthConsumer("tOzL5hTkSz9KiA2RIAECW4g7Uq","cj8HLPmBKnRAsffLe5qpQIZ9Y");
        consumer.setTokenWithSecret(null, null); //i pass token as access token as a null as my server dont need it.

        URL url = new URL("http://api.seatseller.travel/blockTicket");
          request = (HttpURLConnection) url.openConnection();
        request.setDoOutput(true);   
        request.setRequestMethod("GET"); 
        request.setUseCaches(false);  
        request.setConnectTimeout(10000);  
        request.setReadTimeout(10000);  
        request.setRequestProperty("Content-Type","application/json");   

        request.setRequestProperty("Host", "android.schoolportal.gr");


        consumer.sign(request);
        request.connect();
        OutputStreamWriter out = new   OutputStreamWriter(request.getOutputStream());
        out.write(jsonParam.toString());
        out.close();  
        int HttpResult =request.getResponseCode();  
        if(HttpResult ==HttpURLConnection.HTTP_OK){  
            BufferedReader br = new BufferedReader(new InputStreamReader(  
                    request.getInputStream(),"utf-8"));  
            String line = null;  
            while ((line = br.readLine()) != null) {  
                sb.append(line + "\n");  
            }  
            br.close();  

            System.out.println(""+sb.toString());  

        }else{  
                System.out.println(request.getResponseMessage());  
        }  
    } catch (MalformedURLException e) {  

             e.printStackTrace();  
    }  
    catch (IOException e) {  

        e.printStackTrace();  
        } 
     catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
public class JSONParser {
    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";

    public JSONParser() {

    }
    public JSONObject makeHttpRequest(String url, String method,
                                      List<NameValuePair> params) {


        try {
            if(method == "POST"){
                DefaultHttpClient httpClient = new DefaultHttpClient();
                HttpPost httpPost = new HttpPost(url);
                httpPost.setEntity(new UrlEncodedFormEntity(params));

                HttpResponse httpResponse = httpClient.execute(httpPost);
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();

            }else if(method == "GET"){
                DefaultHttpClient httpClient = new DefaultHttpClient();
                String paramString = URLEncodedUtils.format(params, "utf-8");
                url += "?" + paramString;
                HttpGet httpGet = new HttpGet(url);

                HttpResponse httpResponse = httpClient.execute(httpGet);
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();
            }

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            json = sb.toString();
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }


        try {
            jObj = new JSONObject(json);
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }
        return jObj;

    }
}

然后创建AsyncTask Class上传数据到server.Then 添加这段代码。

JSONParser jsonParser = new JSONParser();

@Override
    protected String doInBackground(String... strings) {
        String message="";        
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("value1", value1));

        JSONObject json = jsonParser.makeHttpRequest(SERVER_URL,
                "POST", params);
        try {
                message=json.getString("message");
                Log.e("msg",message);

        }catch (JSONException e) {
            e.printStackTrace();
        }
        return message ;
    }

value1 发送到服务器。

先生……dhiraj kakran 我在 android sdk 本身也遇到了同样的问题,一个错误是那里我的意思是在 post 请求使用 oauthentication 的情况下限制网络请求我们无法使用 HttpUrlConnection oauth 登录 post 请求,特别是 post 使用 oauth 的签名方法 我们使用默认的 HttpClient class 我正在为此提供解决方案,现在您可以通过此获得响应 class祝你好运

public class BlockTicketPostOauth extends AsyncTask<String, Void, Integer> {
    ProgressDialog pd;
    String response;
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pd=new ProgressDialog(BusPassengerInfo.this);
        pd.setMessage("wait continue to payment....");
        pd.show();

    }

    @Override
    protected Integer doInBackground(String... params) {
        InputStream inputStream = null;
        String ul ="http://api.seatseller.travel/blockTicket";

        String  JSONPayload=params[0]; // THIS IS THE JSON DATA WHICH YOU WANT SEND TO THE SERVER 
        Integer result = 0;
        try {

            OAuthConsumer consumer = new CommonsHttpOAuthConsumer(YOUR CONSUMER KEY,YOUR CONSUMER SECRETE KEY); consumer.setTokenWithSecret(null, null);

            /* create Apache HttpClient */
            HttpClient httpclient = new DefaultHttpClient();

            /* Httppost Method */
            HttpPost httppost = new HttpPost(ul);

            // sign the request
            consumer.sign(httppost);

            // send json string to the server
            StringEntity paras =new StringEntity(JSONPayload);

            //seting the type of input data type
            paras.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));

            httppost.setEntity(paras);

            HttpResponse httpResponse= httpclient.execute(httppost);

            int statusCode = httpResponse.getStatusLine().getStatusCode();

            Log.i("response json:","status code is:"+statusCode);
            Log.i("response json:","status message?:"+httpResponse.getStatusLine().toString());

            /* 200 represents HTTP OK */
            if (statusCode ==  200) {
                /* receive response as inputStream */
                inputStream = httpResponse.getEntity().getContent();
                response = convertInputStreamToString(inputStream);

                Log.i("response json:","json response?:"+response);

                Log.i("response block ticket :","status block key:"+response);

                result = 1; // Successful
            } else{
                result = 0; //"Failed to fetch data!";
            }
        } catch (Exception e) {
            Log.d("response error", e.getLocalizedMessage());
        }
        return result; //"Failed to fetch data!";
    }

    @Override
    protected void onPostExecute(Integer result) {

        if(pd.isShowing()){
            pd.dismiss();
        }
        /* Download complete. Lets update UI */
        if(result == 1){


            Toast.makeText(BusPassengerInfo.this,"response is reult suceess:"+response,Toast.LENGTH_SHORT).show();

        //allowing the customer to going to the payment gate way

        }else{
            Log.e("response", "Failed to fetch data!");
            Toast.makeText(BusPassengerInfo.this,"response is reult fail",Toast.LENGTH_SHORT).show();
        }

    }
}