有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何向POST restful服务发送json数据

我想用POST方法调用rest Web服务。下面是我需要传递的服务url及其参数

 Rest Service: https://url/SSOServer/SSO.svc/RestService/Login

Json Object {"ProductCode":"AB","DeviceType":"安卓 Simulator","UserName":"","ModuleCode":"AB_MOBILE","DeviceId":"device-id","Version":"1.0.0.19","CustomerCode":"w","Password":""}

这是我的发帖代码:

public void sendHttpPost() throws ClientProtocolException, IOException{
        HttpPost httpPostRequest = new HttpPost(url + buildParams());

        // add headers
        Iterator it = headers.entrySet().iterator();
        Iterator itP = params.entrySet().iterator();
        while (it.hasNext()) {
            Entry header = (Entry) it.next();
            httpPostRequest.addHeader((String)header.getKey(), (String)header.getValue());
        }

        HttpClient client = new DefaultHttpClient();
        HttpResponse resp;

        resp = client.execute(httpPostRequest);

        this.respCode = resp.getStatusLine().getStatusCode();
        Log.i(TAG, "response code: " + getResponseCode());
        this.responsePhrase = resp.getStatusLine().getReasonPhrase();
        Log.i(TAG, "error msg: " + getErrorMsg());
        HttpEntity entity = resp.getEntity();

        if (entity != null){
            InputStream is = entity.getContent();
            //Header contentEncoding = resp.getFirstHeader("Content-encoding");
            //Log.i(TAG, "endoding" + contentEncoding.getValue());
            response = convertStreamToString(is);
            //response = response.substring(1,response.length()-1);
            //response = "{" + response + "}";
            Log.i(TAG, "response: " + response);
            is.close();
        }
    }

我的问题是如何向这个请求中添加json数据


共 (0) 个答案