【问题标题】:Tell me how to send the Json request告诉我如何发送 Json 请求
【发布时间】:2015-01-28 09:37:32
【问题描述】:

我正在发送json请求代码给出错误有什么办法吗 发送带有身份验证的 json 请求。此代码给出错误 在文件中未找到“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();
    }

【问题讨论】:

  • 请用错误描述更新您的问题,没有它什么都不是
  • 我们不知道也无法猜测st 参数是什么。
  • 你好先生..st是json对象..
  • 此代码发送文件未找到异常............

标签: android json http connection


【解决方案1】:
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 发送到服务器。

【讨论】:

  • 此代码运行良好,您只需要创建 AsyncTask 并添加第二个代码。这个用于发送 POST 变量。您必须将其更改为 GET。
  • 亲爱的,我尝试了很多发送请求的方式
  • 在此之前确定您的服务器工作正常。您可以使用 CURL 请求检查服务器。
【解决方案2】:

看先生...dhiraj kakran 我在 android sdk 本身也遇到了同样的问题 一个错误是我的意思是在使用 oauthentication 发布请求的情况下限制网络请求,我们无法使用 HttpUrlConnection 对发布请求进行 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();
        }

    }
}

【讨论】: