从Android发送JSON HTTP POST请求

44
我正在使用以下代码发送HTTP POST请求,该请求向WCF服务发送一个对象。这个代码可以正常工作,但是如果我的WCF服务还需要其他参数,应该怎么办?我该如何从Android客户端发送它们?
这是我迄今为止编写的代码:
StringBuilder sb = new StringBuilder();  

String http = "http://android.schoolportal.gr/Service.svc/SaveValues";  


HttpURLConnection urlConnection=null;  
try {  
    URL url = new URL(http);  
    urlConnection = (HttpURLConnection) url.openConnection();
    urlConnection.setDoOutput(true);   
    urlConnection.setRequestMethod("POST");  
    urlConnection.setUseCaches(false);  
    urlConnection.setConnectTimeout(10000);  
    urlConnection.setReadTimeout(10000);  
    urlConnection.setRequestProperty("Content-Type","application/json");   

    urlConnection.setRequestProperty("Host", "android.schoolportal.gr");
    urlConnection.connect();  

    //Create JSONObject here
    JSONObject jsonParam = new JSONObject();
    jsonParam.put("ID", "25");
    jsonParam.put("description", "Real");
    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{  
            System.out.println(urlConnection.getResponseMessage());  
    }  
} catch (MalformedURLException e) {  

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

    e.printStackTrace();  
    } catch (JSONException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}finally{  
    if(urlConnection!=null)  
    urlConnection.disconnect();  
}  

请点击以下链接。如果您想发送其他参数,请参考下面的演示,了解如何在编码后发送它们:http://www.xyzws.com/Javafaq/how-to-use-httpurlconnection-post-data-to-web-server/139 - Amir Qayyum Khan
2个回答

58

发布参数使用POST:

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.writeBytes(URLEncoder.encode(jsonParam.toString(),"UTF-8"));
printout.flush ();
printout.close ();

剩下的事情你可以做到。


20
DataOutputStream 类中的 write(int) 方法不适用于参数 (String)。 - user1940676
12
我使用了以下代码替换了write(int)方法: String str = jsonString.toString(); byte[] data=str.getBytes("UTF-8"); printout.write(data); printout.flush (); printout.close (); 现在它可以正常工作。 - Thirumalvalavan
1
这是一个旧答案,但对我来说非常有效,可以摆脱已弃用的DefaultHttpClient。我还从已弃用的NameValuePair转移到了JSON对象。顺便说一下,我不得不将“write”更改为“writeBytes”。 - G O'Rilla
printout.write(URLEncoder.encode(jsonParam.toString(),"UTF-8")); 我们直接将 jsonObject 传递给服务器。 - Harish
1
我之前遇到了上述错误,即printout.write()的参数类型错误,因此我使用了printout.writeUTF(URLEncoder.encode(params.toString(), "UTF-8"))。 - jperl
显示剩余6条评论

14

尝试一些像以下的事情:

SString otherParametersUrServiceNeed =  "Company=acompany&Lng=test&MainPeriod=test&UserID=123&CourseDate=8:10:10";
String request = "http://android.schoolportal.gr/Service.svc/SaveValues";

URL url = new URL(request); 
HttpURLConnection connection = (HttpURLConnection) url.openConnection();   
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setInstanceFollowRedirects(false); 
connection.setRequestMethod("POST"); 
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); 
connection.setRequestProperty("charset", "utf-8");
connection.setRequestProperty("Content-Length", "" + Integer.toString(otherParametersUrServiceNeed.getBytes().length));
connection.setUseCaches (false);

DataOutputStream wr = new DataOutputStream(connection.getOutputStream ());
wr.writeBytes(otherParametersUrServiceNeed);

   JSONObject jsonParam = new JSONObject();
jsonParam.put("ID", "25");
jsonParam.put("description", "Real");
jsonParam.put("enable", "true");

wr.writeBytes(jsonParam.toString());

wr.flush();
wr.close();

参考文献:

  1. 如何使用HTTPURLConnection向Web服务器提交POST数据
  2. Java - 通过POST方法轻松发送HTTP参数

我已经这样做了,但服务器响应仍然是错误的请求。现在让我问一下,我是否做得正确:当我设置其他参数时,我应该放置param1还是我的参数名称?另外,我的JSON对象是第一个参数,所以我先写这个,然后再写其他参数,这样对吗? - Libathos
在服务器端,参数序列不重要。看起来你正在将JSON放入有效载荷中... 在这个 otherParametersUrServiceNeed = "param1=a&param2=b&param3=c"; 中,放置你的服务器需要的参数名称,这只是一个例子...你应该首先确定请求中服务器需要的参数,然后像我的示例一样将这些参数及其值添加到 String otherParametersUrService 中。 - Amir Qayyum Khan
这是方法签名,可以告诉你吗?:long InsertStudentAbsences(SRV_Students_Absence objStudentAbsences, string Company, string Lng, string MainPeriod, string UserID, string CourseDate); - Libathos
假设参数完全映射到函数参数。这些是您需要的参数:String otherParametersUrServiceNeed = Company=acompany&Lng=test&MainPeriod=test&UserID=123&CourseDate=xyz - Amir Qayyum Khan
你将传递其他参数,就像JSON对象一样...就像HTTP请求一样,将参数和值排列在字符串中String otherParametersUrServiceNeed =" Company = acompany&Lng = test&MainPeriod = test&UserID = 123&CourseDate = 8:10:10";,并在请求上编写该字符串。就像示例所示。服务器应该能够将这些参数名称映射到字符串“Company”等。您必须在服务器端定义映射。 - Amir Qayyum Khan
显示剩余11条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接