我正在尝试将数据从加速计发送到mysql服务器(通过php脚本)。首先,我使用了DefaultHttpClient,但我只能发送有限的数据,我读到使用HttpURLConnection我可以发送大数据(我主要关心的问题),所以我决定更改代码以使用HttpURLConnect,但我不知道我的JSONArray放在哪里。有人能帮忙吗?
旧代码:
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://192.168.1.5/Android/vals.php");
......
JSONArray postjson=new JSONArray();
postjson.add(jsonx);
postjson.add(jsony);
postjson.add(jsonz);
....
httppost.setHeader("json",jsonx.toString());
httppost.setHeader("jsony",jsony.toString());
httppost.setHeader("jsonz",jsonz.toString());
httpclient.execute(httppost);
新代码:
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput (true);
connection.setDoOutput (true);
connection.setUseCaches (false);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type","application/json; charset=utf8");
connection.connect();
我不知道应该在哪里设置我的JSONArray数据,就像我在下面的代码中所做的那样。谢谢
编辑
最后,我使用DefaultHttpClient实现了这一点,但我没有通过标头发送JSONArray,而是执行了以下操作:
String jsonx = new Gson().toJson(param[0]); //This is inside asynctask
String jsony = new Gson().toJson(param[1]);
String jsonz = new Gson().toJson(param[2]);
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://192.168.1.5/Android/va.php");
try
{
ArrayList<BasicNameValuePair> localArrayList = new ArrayList<BasicNameValuePair();
localArrayList.add(new BasicNameValuePair("json",jsonx.toString()));
localArrayList.add(new BasicNameValuePair("jsony",jsony.toString()));
localArrayList.add(new BasicNameValuePair("jsonz",jsonz.toString()));
try {
httppost.setEntity(new UrlEncodedFormEntity(localArrayList));
String str = EntityUtils.toString(httpclient.execute(httppost).getEntity());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
如果有人遇到类似的麻烦,我会把它发布出来,我可以帮上忙。
http请求使用android
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://url.com/file.php?a=abc&b=123&c=123");
try {
HttpResponse response = httpclient.execute(httppost);
StatusLine statusLine = response.getStatusLine();
System.out.println("new respos "
+ statusLine.getStatusCode() + " "
+ statusLine.toString());
} catch (ClientProtocolException e) {
e.printStackTrace();
}// process execption }
catch (IOException e) {
e.printStackTrace();
}
php代码
<?php
$a= $_GET['a'];
$b= $_GET['b'];
$c= $_GET['c'];
?>