我在app中使用基本正宗的http连接。应用程序在具有更高版本的设备上正确运行finr。我也搜索了解决方案,它对我没用。 这是我的连接代码
public static String executeHttpPost(Activity activity, String url,
ArrayList<NameValuePair> postParameters) {
String value = "{\"status\":false,\"message\":\"Server Timeout, connection problem, Please try later\"}";
try {
final String basicAuth = "Basic " + Base64.encodeToString(
("abc" + ":" + "abcd").getBytes(), Base64.NO_WRAP);
networkConnection = new NetworkConnection();
if (networkConnection.isOnline(activity)) {
postParameters.add(new BasicNameValuePair("device_type","android"));
HttpClient client = getNewHttpClient();
HttpPost post = new HttpPost(url);
try {
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(postParameters, "UTF-8");
post.setEntity(entity);
post.setHeader("Authorization",basicAuth);
post.setHeader("some-parameter","abc");
org.apache.http.HttpResponse result = client.execute(post);
value = EntityUtils.toString(result.getEntity());
}catch (Exception e){}
String s = "";
for (NameValuePair param : postParameters) {
s = s + param.getName() + " = " + param.getValue() + " ";
}
if (value != null) {
WebUrl.ShowLog("From " + url +" parameters "+s
+ " Response : " + value.trim());
return value.trim();
} else {
return value;
}
} else {
activity.startActivity(new Intent(activity, NoInternet.class));
activity.finish();
return "{\"status\":false,\"message\":\"\"}";
}
} catch (Exception e) {
e.printStackTrace();
return value;
}
}
答案 0 :(得分:0)
您应该使用Google Volley与服务器建立连接。有很多方法可以获得连接,但在Android开发中使用“Google Volley”非常简单,可靠,并且它作为依赖项与您的软件包捆绑在一起。因此,永远不要担心许多旧的和许多当前和即将推出的Android版本的兼容性。
我在5年前使用它,它正在所有主要平台上工作。非常容易编程。
看看:
final TextView mTextView = (TextView) findViewById(R.id.text);
// Instantiate the RequestQueue.
RequestQueue queue = Volley.newRequestQueue(this);
String url ="http://www.google.com";
// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>()
{
@Override
public void onResponse(String response)
{
// Display the first 500 characters of the response string.
mTextView.setText("Response is: "+ response.substring(0,500));
}
}, new Response.ErrorListener()
{
@Override
public void onErrorResponse(VolleyError error)
{
mTextView.setText("That didn't work!");
}
});
// Add the request to the RequestQueue.
queue.add(stringRequest);
它有多简单。