java - Android 在将 json 发布到 web 服务时发送空参数

标签 java android json web-services httpurlconnection

请帮助我,我在使用 HttpUrlConnection 类发送 JSON 对象作为参数体的 POST 请求时遇到问题。我一直在 SO 中寻找同样的问题,我已经尝试了解决方案,但没有一个适用于我的情况。这是我的代码(我在 AsyncTask 类中调用此方法):`

 public JSONObject postData(String url, JSONObject params) throws IOException{
    JSONObject ret=null;
    OutputStream os=null;
    InputStream is=null;
    HttpURLConnection cnHost=null;
    URL host=null;
    String jsStr=null;
    StringBuilder result=null;
    String json="";

    try {

        //TODO Open host connection
        host = new URL(url);
        jsStr = "key="+params;
        cnHost = (HttpURLConnection) host.openConnection();

        //TODO set request Attribute
            //Set Connection attributes
            cnHost.setDoInput(true);
            cnHost.setDoOutput(true);
            cnHost.setUseCaches (false);
            cnHost.setAllowUserInteraction(false);
            cnHost.setReadTimeout(10000);
            cnHost.setConnectTimeout(15000);
            cnHost.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;");
            cnHost.setRequestMethod("POST");

        //TODO Start streaming request
        cnHost.connect();

        os =cnHost.getOutputStream();
        BufferedWriter wr = new BufferedWriter(new OutputStreamWriter(os));
        wr.write(jsStr);
        wr.flush();
        wr.close();

        //TODO get Response
        try {
                BufferedInputStream in = new BufferedInputStream(cnHost.getInputStream());
                BufferedReader reader = new BufferedReader(new InputStreamReader(in));
                result = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null) {
                    result.append(line); }

                //TODO cast to json Object
                json = result.toString();
                in.close();
                reader.close();

                ret = new JSONObject(json);
        } catch (Exception e){
            Log.d("Get_response","inner_Exception");
            e.printStackTrace();
        }



    }catch (IOException e) {
        //TODO Add IOException Handler
        Log.d("IOException", "Descp:");
        e.printStackTrace();
    }catch (NullPointerException e){
        //TODO Add NUllPointerException
        Log.d("NullPointerException","Descp:");
        e.printStackTrace();
    } catch (Exception e){
        //TODO Add Exception Handler
        Log.d("Exception","Descp");
        e.printStackTrace();
    } finally {

        //region Log postData (removed when no bug)
            Log.d("bodyContent:", jsStr);
            Log.d("RequestMethod", cnHost.getRequestMethod());
            Log.d("DoInput", String.valueOf(cnHost.getDoInput()));
            Log.d("DoOutput", String.valueOf(cnHost.getDoOutput()));
            Log.d("FixLengthStreamMode", String.valueOf(jsStr.getBytes().length));
            Log.d("Content-Type", cnHost.getRequestProperty("Content-Type"));
            Log.d("Response_Message",json);
        //endregion
        cnHost.disconnect();
    }

    return ret;
}   `

下面是我调用上面方法的代码:

try{
    JSONObject jsParam=new JSONObject();
jsParam.put("method", URLEncoder.encode("check","UTF-8"));

JSONObject jsResponse=postData(myUrl,jsParam);
} catch (Exception e){
    e.printStackTrace;
} finally{
    if(jsObj==null){
            Log.d("NullJson","Yes, jsObj return null");
        }  else {
            Log.d("ValidResponse",jsObj.toString());
        }
}

当此请求从 android-app 发布时,web-service 始终响应所述请求正文包含的是空消息。但是当我使用 postman 客户端发送它时,网络服务响应有效消息。在我的 postman 代码下方:

POST /mro/public/index.php? HTTP/1.1
Host: mro.alfamartku.com
Content-Type: application/x-www-form-urlencoded;
Cache-Control: no-cache
Postman-Token: 25463d97-b821-7016-d3e7-5e256d69a31a

key={"method":"check"}

最佳答案

URL url;
URLConnection urlConn;
DataOutputStream printout;
DataInputStream  input;
url = new URL (getCodeBase().toString() + "env.tcgi");
urlConn = url.openConnection();
urlConn.setDoInput (true);
urlConn.setDoOutput (true);
urlConn.setUseCaches (false);
urlConn.setRequestProperty("Content-Type","application/json");   
urlConn.setRequestProperty("Host", "android.schoolportal.gr");
urlConn.connect();  
//Create JSONObject here
JSONObject jsonParam = new JSONObject();
jsonParam.put("ID", "25");
jsonParam.put("description", "Real");
jsonParam.put("enable", "true");

你错过的部分在下面......即,如下......

// Send POST output.
printout = new DataOutputStream(urlConn.getOutputStream ());
printout.write(URLEncoder.encode(jsonParam.toString(),"UTF-8"));
printout.flush ();
printout.close ();

剩下的事情你可以自己做。

关于java - Android 在将 json 发布到 web 服务时发送空参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37410498/

相关文章:

java - 如何在android中读取XML数据

json - 下载后如何打印自定义 JSON 对象值?

Java:Protobuf字节到Json字符串到Pojo快速

java - RMI客户端方法调用

java - 将静态ArrayList中的数据插入到mySql数据库中的表中

android - 将字符串从 Android Java Activity 传递到广播接收器

javascript - 执行ajax时如何将javascript变量值传递给jQuery validate() SubmitHandler

java - 使用单个元素区分 String 列表和 String[] 列表

java - java构造函数中的自赋值

android - 无法使用位于不同目录中的头文件