Java 带有json字符串的Android HttpURLConnection

Java 带有json字符串的Android HttpURLConnection,java,android,Java,Android,我想调用以下URL: http://192.168.0.196:8080/openapi/localuser/set?{"syskey":"1234","usrname":"256","usrpwd":"556"} 使用此地址向数据库添加新用户。为此,我在AsyncTask类中使用HttpURLConnection try { URL myUrl = new URL(params[0]); HttpURLConnection c

我想调用以下URL:

http://192.168.0.196:8080/openapi/localuser/set?{"syskey":"1234","usrname":"256","usrpwd":"556"}
使用此地址向数据库添加新用户。为此,我在
AsyncTask
类中使用
HttpURLConnection

try {

                URL myUrl = new URL(params[0]);
                HttpURLConnection conn = (HttpURLConnection) myUrl.openConnection();
                conn.setReadTimeout(10000 );
                conn.setConnectTimeout(15000);
                conn.setRequestMethod("POST");
                conn.setDoInput(true);
                // Starts the query
                conn.connect();
                int response = conn.getResponseCode();

                Log.d("lab", "The response is: " + response);

                statusMap.put("addUser", Integer.toString(response));

                Log.d("lab", "URL: " + params[0]);

            }catch (Exception e){
                Log.d("lab", "Error2: " + e.getMessage());
            }
params[0]=http://192.168.0.196:8080/openapi/localuser/set?{“syskey”:“1234”,“usrname”:“256”,“usrpwd”:“556”}

不幸的是,这个电话不起作用。我不明白这个错误。
catch
返回null

这样试试。您需要在代码中添加几行

public JSONObject makeHttpRequest(String requestURL, JSONObject register) {

        try {

            url = new URL(requestURL);

            connection = (HttpURLConnection) url.openConnection();

            connection.setReadTimeout(150000);
            connection.setConnectTimeout(150000);

            connection.setAllowUserInteraction(true);
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Accept-Charset", "UTF-8");
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            connection.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
            connection.setFixedLengthStreamingMode(register.toString().getBytes().length);
            connection.setDoInput(true);
            connection.setDoOutput(true);
            OutputStreamWriter outputStream = new OutputStreamWriter(connection.getOutputStream());

            outputStream.write(register.toString());

            outputStream.flush();

            Log.e("URL", connection.getURL().toString());
            Log.e("JSONObject", register.toString());
        } catch (Exception e) {
            Log.e("MAIN Exception", e.toString());
        }
        try {

            int statuscode = connection.getResponseCode();

            if (statuscode == HttpURLConnection.HTTP_OK) {
                is = connection.getInputStream();
            } else {

            }
        } catch (IOException e) {
            Log.e("IOException", e.toString());
        }

        try {

            rd = new BufferedReader(new InputStreamReader(is));

            response = new StringBuffer();

            while ((line = rd.readLine()) != null) {
                response.append(line);
                response.append('\n');
            }
            Log.e("Response", response.toString() + " ");

            rd.close();
        } catch (IOException e) {
            Log.e("BUFFER_READER", e.toString());
        } catch (NullPointerException e) {
            Log.e("NullPointerException", e.toString());
        } finally {
            connection.disconnect();
        }

        try {


            return new JSONObject(response.toString());
        } catch (JSONException e) {
            Log.e("JSONException", e.toString());

        }
        return null;
    }
此外,如果您使用的是localHost,则必须具有可以连接到localHost的emulator。除非它无法在任何设备上工作。

请尝试以下操作:

 private String post(String url) throws JSONException {
    JSONObject json = new JSONObject();
    try {
        String query = "";
        String EQ = ":";
        String AMP = "&";
        for (NameValuePair param : parameters) {
            query = json.put(param.getName(), param.getValue()) + ",";

        }

        // url+= "?" + query;
        HttpClient client = new DefaultHttpClient();
        HttpPost post = new HttpPost(url);

        if (parameters != null) {

            StringEntity se = new StringEntity(query.toString());
            se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE,
                    "application/json"));

            post.setEntity(se);

            Log.d("POSTQuery", url + parameters);
        }

        HttpResponse response = client.execute(post);
        StatusLine statusLine = response.getStatusLine();
        Log.d("Status Code", "" + statusLine.getStatusCode());
        if (statusLine.getStatusCode() == 200) {
            return StringifyResponse(response);
        }

        Log.d("POSTQuery", url);

        // Log.d("response", response.toString());
        return StringifyResponse(response);

    } catch (ClientProtocolException e) {
    } catch (IOException e) {
        Log.d("response", e.toString());
        return "IOException";
    }

    return null;
}

您需要格式化所有url查询字符串,然后使用outputwriter刷新数据:

// Create data variable for sent values to server  

        String data = URLEncoder.encode("syskey", "UTF-8") 
                     + "=" + URLEncoder.encode("1234", "UTF-8"); 

        data += "&" + URLEncoder.encode("usrname", "UTF-8") + "="
                    + URLEncoder.encode("256", "UTF-8"); 

        data += "&" + URLEncoder.encode("usrpwd", "UTF-8") 
                    + "=" + URLEncoder.encode("556", "UTF-8");
然后刷新数据:

        URLConnection conn = url.openConnection(); 
        conn.setDoOutput(true); 
        OutputStreamWriter wr = new  OutputStreamWriter(conn.getOutputStream()); 
        wr.write( data ); 
        wr.flush(); 
链接此处:
HttpClient
现在已不推荐使用。你不应该使用它。是的,正如Android开发者所提到的@Minhtdh,你是对的,它从API级别22被弃用了。从你的
param
链接中,我认为你只需要
conn.setRequestMethod(“GET”)并且不需要
conn.setDoInput(true)。除此之外,您应该使用“Log.getStackTraceString(e)”而不是
e.getMessage()
,然后在此处添加logcat。当我删除
conn.setDoInput(true)
时,我的代码正在工作。谢谢