使用android从fiddler复制HttpPost请求

时间:2012-12-05 15:32:13

标签: android json wcf http-post

我已经使用json构建了一个wcf服务。我认为它工作正常,因为我已经用fiddler调试它。我不能从android正确调用它。我想我必须是在尝试传递参数时做错了。这是小提琴请求:

请求标题:

User-Agent:Fiddler 主持人:androidwcf.schoolportal.gr Content-Type:application / json 内容长度:73

请求正文:

{     " ID":2147483647,     " description":"字符串内容",     "使":真 }

如何将这个json对象作为android的参数传递? 谢谢你的时间。

1 个答案:

答案 0 :(得分:1)

尝试将当前的json对象发布到您的服务器:

    StringBuilder sb = new StringBuilder();  

    String http = "YOUR_WEB_URL";  
    //System.out.println("-----------------" + http+"?"+param);  
    HttpURLConnection urlConnection=null;  
    try {  
        URL url = new URL(http);  
         urlConnection = (HttpURLConnection) url  
                .openConnection();
        urlConnection.setDoOutput(true);   
        urlConnection.setRequestProperty("User-Agent", "Fiddler");  
        urlConnection.setRequestMethod("POST");  
        urlConnection.setUseCaches(false);  
        urlConnection.setConnectTimeout(10000);  
        urlConnection.setReadTimeout(10000);  
        urlConnection.setRequestProperty("Content-Type","application/json");   
        urlConnection.setRequestProperty("Content-Length","73");
        urlConnection.setRequestProperty("Host", "androidwcf.schoolportal.gr");
        urlConnection.connect();  

         //Create JSONObject here
        JSONObject jsonParam = new JSONObject();
        jsonParam.put("ID", "25");
        jsonParam.put("description", "String content");
        jsonParam.put("enable", "true");
        OutputStreamWriter out = new   OutputStreamWriter(urlConnection.getOutputStream());
        out.write(jsonParam.toString());
        out.close();  

        int HttpResult =urlConnection.getResponseCode();  
        if(HttpResult ==HttpURLConnection.HTTP_OK){  
            BufferedReader br = new BufferedReader(new InputStreamReader(  
                    urlConnection.getInputStream(),"utf-8"));  
            String line = null;  
            while ((line = br.readLine()) != null) {  
                sb.append(line + "\n");  
            }  
            br.close();  

                System.out.println(""+sb.toString());  

        }else{  
            log.warn(urlConnection.getResponseMessage());  
        }  
    } catch (MalformedURLException e) {  

        e.printStackTrace();  
    }  
    catch (IOException e) {  

        e.printStackTrace();  
    }finally{  
        if(urlConnection!=null)  
           urlConnection.disconnect();  
    }  

}