我用这个代码发送后数据到服务器使用android。有人能给我任何想法或您的示例如何发送POST或GET json数据到服务器TOMCAT...!步骤提示:
>
返回结果
private class HttpAsyncTask extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... urls) {
person = new Person();
person.setName(etName.getText().toString());
person.setCountry(etCountry.getText().toString());
person.setTwitter(etTwitter.getText().toString());
return POST(urls[0],person);
}
// onPostExecute displays the results of the AsyncTask.
@Override
protected void onPostExecute(String result) {
Toast.makeText(getBaseContext(), "Data Sent!", Toast.LENGTH_LONG).show();
}
}
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
static String responseString;
// constructor
public JSONParser() {
}
// function get json from url
// by making HTTP POST or GET mehtod
public static JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
// Making HTTP request
Log.d("json class", url + "," + method + "," + params.toString());
try {
// check for request method
if (method == "POST") {
// request method is POST
// defaultHttpClient
Log.d("json class", "post method");
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
Log.d("json class", "HttpPost" + httpPost);
httpPost.setEntity(new UrlEncodedFormEntity(params));
Log.d("json class", "setentity");
HttpResponse httpResponse = httpClient.execute(httpPost);
ByteArrayOutputStream out = new ByteArrayOutputStream();
int responce_code = httpResponse.getStatusLine()
.getStatusCode();
Log.d("responce code", "response method");
Log.d("responce code", "" + responce_code);
StatusLine statusLine = httpResponse.getStatusLine();
if (statusLine.getStatusCode() == HttpStatus.SC_OK) {
Log.i("RESPONSE", "6");
/*
* httpResponse.getEntity().writeTo(out); out.close();
* String responseString = out.toString(); Log.i("RESPONSE",
* ""+responseString);
*/
// ..more logic
} else {
Log.d("RESPONSE", "null pointer exception");
// Closes the connection.
httpResponse.getEntity().getContent().close();
throw new IOException(statusLine.getReasonPhrase());
}
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} else if (method == "GET") {
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
Log.i("url", url);
HttpGet httpGet = new HttpGet(url);
ByteArrayOutputStream out = new ByteArrayOutputStream();
HttpResponse httpResponse = httpClient.execute(httpGet);
int responce_code = httpResponse.getStatusLine()
.getStatusCode();
Log.d("responce code", "response method");
Log.d("responce code", "" + responce_code);
StatusLine statusLine = httpResponse.getStatusLine();
if (statusLine.getStatusCode() == HttpStatus.SC_OK) {
Log.d("RESPONSE", "6");
httpResponse.getEntity().writeTo(out);
Log.d("RESPONSE", "7");
out.close();
Log.d("RESPONSE", "8");
responseString = out.toString();
Log.d("RESPONSE", "9");
Log.i("RESPONSE", "" + responseString);
// ..more logic
} else {
Log.d("RESPONSE", "null pointer exception");
// Closes the connection.
httpResponse.getEntity().getContent().close();
throw new IOException(statusLine.getReasonPhrase());
}
/*
* HttpEntity httpEntity = httpResponse.getEntity(); is =
* httpEntity.getContent();
*/
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
/*
* BufferedReader reader = new BufferedReader(new InputStreamReader(
* is, "iso-8859-1"), 8); StringBuilder sb = new StringBuilder();
* String line = null; while ((line = reader.readLine()) != null) {
* sb.append(line + "\n"); } is.close();
*/
json = responseString.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
如果你需要获取数据,试试这个。。。
try{
URL url = new URL("http://www.youraddresheredude.com/andthefile");
//Open the connection here, and remember to close it when job its done.
URLConnection conn = url.openConnection();
conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
//theJSONYouWantToSend should be the JSONObject as String
wr.write(convertStandardJSONString(theJSONYouWantToSend)); //<--- sending data.
wr.flush();
// Here you read any answer from server.
BufferedReader serverAnswer = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = serverAnswer.readLine()) != null) {
System.out.println("LINE: " + line); //<--If any response from server
//use it as you need, if server send something back you will get it here.
}
wr.close();
serverAnswer.close();
} catch (Exception e) {
Log.e("Cuack", "Something its wrong");
}
您正在使用HttpClient。实际上,Android不支持HttpClient嵌入HttpClient,您需要“HttpURLConnection”进行POST请求检查这里有一个示例:这里
更新:
为了达到您的要求,您需要为示例代码添加以下两行代码。
conn.addRequestProperty("Accept", "application/json");
conn.addRequestProperty("Content-Type", "application/json");
在给定的示例代码中:
conn.setDoOutput(true);
//Add the following line to the given sample
===============> updated for JSON POST <=========================
conn.addRequestProperty("Accept", "application/json");
conn.addRequestProperty("Content-Type", "application/json");
===============> updated for JSON POST <=========================
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("firstParam", paramValue1));
params.add(new BasicNameValuePair("secondParam", paramValue2));
params.add(new BasicNameValuePair("thirdParam", paramValue3));
问题内容: 我有MySQL数据库服务器 我需要通过JSON更新和检索MySQL服务器中的数据 所以,我想知道如何做到这一点,并且让这个示例语句感到困惑: 这意味着我需要先编写与PHP服务器连接的应用程序代码,然后再编写php以连接数据库。 问题答案: 要将数据发送到服务器,您可以执行以下操作: 然后发送让说: 因此服务器上的AddAccelerationData.php文件为: 这是我最近使用的示
问题内容: 我目前正在尝试从Android应用程序向php服务器发送数据(两者均由我控制)。 应用程序中的表单上收集了很多数据,这些数据已写入数据库。所有这一切。 在我的主代码中,首先我创建一个JSONObject(在此示例中,我已在此处将其裁剪): 接下来,我将对象传递给发送对象,并接收响应: HTTPPoster类: 这将获得响应,但是服务器返回403-禁止响应。 我试过稍微更改doPost函
我正在尝试使用POST提交表单,但我有一些来自 标记的额外数据,这些数据已存储到JS对象中。当我从JavaScript中点击时,我想把它发送到服务器。 我尝试做的是用事件发送
问题内容: 我正在尝试通过一个请求将数据从一个node.js服务器发送到另一个node.js服务器。我在“客户端” node.js中执行的操作如下: 该块或多或少是从node.js网站获取的,因此应该正确。我唯一看不到的是如何在变量中包括用户名和密码以进行实际登录。这是我处理服务器node.js中的数据的方式(我使用express): 如何将这些和字段添加到变量中以使其登录? 谢谢 问题答案: 发
问题内容: 我对PHP,JavaScript和许多其他脚本语言有丰富的经验,但是对Java或Android却没有太多的经验。 我正在寻找一种将 POST 数据发送到PHP脚本并显示结果的方法。 问题答案: ***更新了适用于Android 6.0+的答案。 较旧的答案 注意:此解决方案已过时。 它仅适用于最高5.1的Android设备。Android 6.0及更高版本不包含此答案中使用的Apach
问题内容: 我想使用Android将数据发送到我的php页面。我该怎么做? 问题答案: 您可以使用AndroidHttpClient进行GET或POST请求: 创建一个AndroidHttpClient来执行您的请求。 创建一个HttpGet或HttpPost请求。 使用setEntity和setHeader]方法填充请求。 对您的请求使用客户端上的execute方法之一。