使用HttpUrlConnection发送数据

时间:2014-05-05 10:41:19

标签: java json jersey httpurlconnection put

我正在尝试使用rest将数据发送到HttpUrlConnection服务,如下所示:

 public void makePutRequest(String objtype,String objkey,String json)
{
    String uri="http://localhost:8180/GoogleMapsLoadingTest/rest/GoogleMapsErp/"+objtype+"/"+objkey;
    HttpURLConnection conn=null;
    URL url=null;
    BufferedWriter writer=null;
    try {
        url=new URL(uri);   
    } catch (MalformedURLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    try {
        conn=(HttpURLConnection) url.openConnection();
        conn.addRequestProperty("Content-Type", "application/json");
        conn.setRequestMethod("PUT");
        conn.setDoInput(true);
        conn.setDoOutput(true);
        System.out.println(json);
        writer=new BufferedWriter(new OutputStreamWriter(conn.getOutputStream()));
        writer.write(json);
        int rc=conn.getResponseCode();
        System.out.println("The response code is "+rc);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    finally
    {
        if(writer!=null)
        {
            try {
                writer.flush();
                writer.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            if(conn!=null)
                conn.disconnect();
        }
    }

}

I get this error because the String could not be sent over

1 个答案:

答案 0 :(得分:2)

在获得响应代码之前,您需要flush() BufferedWriter