从Android发送JSON HTTP POST请求

我正在使用下面的代码发送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();

}

回答:

使用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 ();

其余的事情你都可以做到。

以上是 从Android发送JSON HTTP POST请求 的全部内容, 来源链接: utcz.com/qa/432925.html

回到顶部