Android正在向服务器发送HTTP POST请求
我正在创建一个连接到cakePHP网站的应用程序 我创建了一个默认的HTTP客户端,并向服务器发送一个HTTP POST请求。 数据以json格式来自服务器,在客户端,我从json数组中获取值,这是我的项目结构。 下面我展示了一些我用来连接服务器的代码Android正在向服务器发送HTTP POST请求,android,web-services,interface,httpclient,Android,Web Services,Interface,Httpclient,我正在创建一个连接到cakePHP网站的应用程序 我创建了一个默认的HTTP客户端,并向服务器发送一个HTTP POST请求。 数据以json格式来自服务器,在客户端,我从json数组中获取值,这是我的项目结构。 下面我展示了一些我用来连接服务器的代码 try{ HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost("h
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://10.0.2.2/XXXX/logins/login1");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs, HTTP.UTF_8));
response = httpclient.execute(httppost);
StringBuilder builder = new StringBuilder();
BufferedReader reader = new BufferedReader
(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
for (String line = null; (line = reader.readLine()) != null;)
{
builder.append(line).append("\n");
}
JSONTokener tokener = new JSONTokener(builder.toString());
JSONArray finalResult = new JSONArray(tokener);
System.out.println("finalresulttttttt"+finalResult.toString());
System.out.println("finalresul length"+finalResult.length());
Object type = new Object();
if (finalResult.length() == 0 && type.equals("both"))
{
System.out.println("null value in the json array");
}
else {
JSONObject json_data = new JSONObject();
for (int i = 0; i < finalResult.length(); i++)
{
json_data = finalResult.getJSONObject(i);
JSONObject menuObject = json_data.getJSONObject("Userprofile");
group_id= menuObject.getString("group_id");
id = menuObject.getString("id");
name = menuObject.getString("name");
}
}
}
catch (Exception e) {
Toast.makeText(FirstMain.this,"exceptionnnnn",Toast.LENGTH_LONG).show();
e.printStackTrace();
}
试试看{
HttpClient HttpClient=新的DefaultHttpClient();
HttpPost HttpPost=新的HttpPost(“http://10.0.2.2/XXXX/logins/login1");
setEntity(新的UrlEncodedFormEntity(nameValuePairs,HTTP.UTF_8));
response=httpclient.execute(httppost);
StringBuilder=新的StringBuilder();
BufferedReader reader=新的BufferedReader
(新的InputStreamReader(response.getEntity().getContent(),“UTF-8”);
for(String line=null;(line=reader.readLine())!=null;)
{
builder.append(行).append(“\n”);
}
JSONTokener tokener=新的JSONTokener(builder.toString());
JSONArray finalResult=新JSONArray(标记器);
System.out.println(“finalResultTTTT”+finalResult.toString());
System.out.println(“最终结果长度”+finalResult.length());
对象类型=新对象();
if(finalResult.length()==0&&type.equals(“两者”))
{
System.out.println(“json数组中的空值”);
}
否则{
JSONObject json_data=new JSONObject();
对于(int i=0;i
我的问题是
请支持我 1您可以编写实用程序类HTTPPoster并封装到HTTPAsyncCall中。在每个活动中使用该类并传递参数 2 URLConnection,但在Android上最好使用AsyncTask,尤其是Android+4 3您可以设置为信任Android端的所有人。。。不太安全 4不,但在android上,清单需要添加权限,比如互联网 5使用Library手动或自动执行有两种方式marshaling、unmarshaling。JSON的开销更小 我希望有帮助 这将帮助您:
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
// function get json from url
// by making HTTP POST or GET method
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) throws Exception {
// Making HTTP request
try {
// check for request method
if (method == "POST") {
// request method is POST
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
// new
HttpParams httpParameters = httpPost.getParams();
// Set the timeout in milliseconds until a connection is
// established.
int timeoutConnection = 10000;
HttpConnectionParams.setConnectionTimeout(httpParameters,
timeoutConnection);
// Set the default socket timeout (SO_TIMEOUT)
// in milliseconds which is the timeout for waiting for data.
int timeoutSocket = 10000;
HttpConnectionParams
.setSoTimeout(httpParameters, timeoutSocket);
// new
HttpResponse httpResponse = httpClient.execute(httpPost);
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;
HttpGet httpGet = new HttpGet(url);
// new
HttpParams httpParameters = httpGet.getParams();
// Set the timeout in milliseconds until a connection is
// established.
int timeoutConnection = 10000;
HttpConnectionParams.setConnectionTimeout(httpParameters,
timeoutConnection);
// Set the default socket timeout (SO_TIMEOUT)
// in milliseconds which is the timeout for waiting for data.
int timeoutSocket = 10000;
HttpConnectionParams
.setSoTimeout(httpParameters, timeoutSocket);
// new
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
} catch (UnsupportedEncodingException e) {
throw new Exception("Unsupported encoding error.");
} catch (ClientProtocolException e) {
throw new Exception("Client protocol error.");
} catch (SocketTimeoutException e) {
throw new Exception("Sorry, socket timeout.");
} catch (ConnectTimeoutException e) {
throw new Exception("Sorry, connection timeout.");
} catch (IOException e) {
throw new Exception("I/O error(May be server down).");
}
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 = sb.toString();
} catch (Exception e) {
throw new Exception(e.getMessage());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
throw new Exception(e.getMessage());
}
// return JSON String
return jObj;
}
}
公共类JSONParser{
静态InputStream为空;
静态JSONObject jObj=null;
静态字符串json=“”;
//建造师
公共JSONParser(){
}
//函数从url获取json
//通过使用HTTP POST或GET方法
公共JSONObject makeHttpRequest(字符串url、字符串方法、,
列表参数)引发异常{
//发出HTTP请求
试一试{
//检查请求方法
如果(方法==“POST”){
//请求方法为POST
//defaultHttpClient
DefaultHttpClient httpClient=新的DefaultHttpClient();
HttpPost HttpPost=新的HttpPost(url);
setEntity(新的UrlEncodedFormEntity(参数));
//新的
HttpParams httpParameters=httpPost.getParams();
//以毫秒为单位设置超时,直到连接断开
//建立。
int timeoutConnection=10000;
HttpConnectionParams.setConnectionTimeout(httpParameters,
超时连接);
//设置默认套接字超时(SO\U超时)
//以毫秒为单位,这是等待数据的超时。
int timeoutSocket=10000;
HttpConnectionParams
.setSoTimeout(httpParameters,timeoutSocket);
//新的
HttpResponse HttpResponse=httpClient.execute(httpPost);
HttpEntity HttpEntity=httpResponse.getEntity();
is=httpEntity.getContent();
}else if(方法==“GET”){
//请求方法是GET
DefaultHttpClient httpClient=新的DefaultHttpClient();
String paramString=URLEncodedUtils.format(params,“utf-8”);
url+=“?”+参数字符串;
HttpGet HttpGet=新的HttpGet(url);
//新的
HttpParams httpParameters=httpGet.getParams();
//以毫秒为单位设置超时,直到连接断开
//建立。
int timeoutConnection=10000;
HttpConnectionParams.setConnectionTimeout(httpParameters,
超时连接);
//设置默认套接字超时(SO\U超时)
//以毫秒为单位,这是等待数据的超时。
int timeoutSocket=10000;
HttpConnectionParams
.setSoTimeout(httpParameters
public class GetName extends AsyncTask<String, String, String> {
String imei = "abc";
JSONParser jsonParser = new JSONParser();
@Override
protected void onPreExecute() {
super.onPreExecute();
}
protected String doInBackground(String... args) {
String name = null;
String URL = "http://192.168.2.5:8000/mobile/";
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", mUsername));
params.add(new BasicNameValuePair("password", mPassword));
JSONObject json;
try {
json = jsonParser.makeHttpRequest(URL, "POST", params);
try {
int success = json.getInt(Settings.SUCCESS);
if (success == 1) {
name = json.getString("name");
} else {
name = null;
}
} catch (JSONException e) {
name = null;
}
} catch (Exception e1) {
}
return name;
}
protected void onPostExecute(String name) {
Toast.makeText(mcontext, name, Toast.LENGTH_SHORT).show();
}
}
<uses-permission android:name="android.permission.INTERNET" />