告诉我如何发送Json请求

时间:2015-01-28 09:37:32

标签: android json http connection

  

我发送json请求代码给出错误是否有任何方法如何   发送带有authentication.this代码的json请求给出错误   在filenotfound" http://api.seatseller.travel/blockTicket"
   // st =   json对象

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

2 个答案:

答案 0 :(得分:0)

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类以将数据上传到服务器。然后添加此代码。

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发送到服务器。

答案 1 :(得分:0)

看看先生... dhiraj kakran我也遇到了同样的问题在android sdk本身就有一个bug我的意思是在使用oauthentication的帖子请求的情况下限制网络请求我们不能使用HttpUrlConnection在post请求中签名oauth对于使用oauth的特殊邮政标志方法我们使用默认的HttpClient类我现在给你的解决方案现在你可以通过这个班得到好运

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

    }
}