我要创建一个连接到CakePHP的网站上的应用程序 我创建默认HTTP客户端,并发送HTTP POST请求到服务器。 这些数据是从JSON格式服务器的到来,并在客户端我拿这个值由JSON数组,这是我的项目结构。 下面我将展示一些code,我曾经与服务器连接
I'm creating an application that connects to the cakePHP website I create a default HTTP client and send a HTTP POST request to the server. The data is coming from the server in json format, and in the client side I take the value from the json array, this is my project structure. Below I show some code that I used to connect with server
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();
}
我的问题是
我需要在每个页面与服务器连接,因为我需要c写的每次$ C $在我的所有活动,是否有任何其他的方式来建立与服务器的连接,从每一个活动发送请求?接口的概念是一样的东西...... 有一个由机器人库连接到服务器提供任何类?任何需要检查所有的验证,如SSL证书,如在客户端? I need to connect every page with the server, for that I need to write the code every time in my all activity, is there any other way to make a connection to the server and send a request from every activity? The concept of an interface is something like.... Is there any class that is supplied by the android library for connecting to the server?
Is any need to check all verification such as an SSL certificate such as in the client-side?
有没有需要连接到服务器,从机器人的任何附加要求?
Are there any additional requirements needed for connecting to a server from android?
什么是服务器执行的服务,如SOAP REST交互的需要
What is the need of implementing services like SOAP REST for interaction with the server
我在这一领域的新鲜..请给我解答了我的疑惑.. 并请大家支持我......
I'm a fresher in this field.. please give me answer for my doubts.. And please support me...
这将帮助你:
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;
}
}
您可以使用上面的类是这样的: 例如:
You can use the above class like this: eg:
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();
}
}
如何使用它: 只是通过复制有关类code创建新JSONParse类。 然后你就可以如图二code(自第二code)在你的应用中调用它的任何。 你需要给清单的权限:
How to use it: Just create new JSONParse class by copying about class code. Then you can call it any where in your application as shown in second code(Customize the second code). You need to give manifest permission:
<uses-permission android:name="android.permission.INTERNET" />
没有必要检查SSL证书。
No need to check SSL certificate.
上一篇:突出显示的android文本视图视图、文本、突出、android
下一篇:logcat的错误内容必须有一个ListView,其id属性是'android.R.id.list“有一个、属性、错误、内容