这个代码让我头疼了两天,在模拟器测试不行,但在2.3手机上测试正常,在4.X手机测试失败,最后发现可能是SDK的原因,请教怎么让其它SDK下也能使用?
< uses-permission android:name="android.permission.INTERNET" />
网络访问权限已经加上
以下代码当build.gradle文件的配置为
minSdkVersion 7
targetSdkVersion 7
正常
当build.gradle文件的配置为
minSdkVersion 9
targetSdkVersion 21
失败
在CSDN找到的资料是SDK3.X,4.X操作HttpClient,需要在子线程执行,这个真不知道该怎么做了。。。
package com.test.module;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class post {
public static String urlpost() {
String URL = "http://localhost/post.php";
HttpPost httpRequest = new HttpPost(URL);
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("action", "测试测试"));
try {
httpRequest.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
HttpResponse httpResponse = new DefaultHttpClient().execute(httpRequest);
if (httpResponse.getStatusLine().getStatusCode() == 200) {
return EntityUtils.toString(httpResponse.getEntity());
} else {
return "连接服务器失败" ;
}
} catch (ClientProtocolException e) {
return "连接服务器失败" ;
} catch (IOException e) {
return "连接服务器失败" ;
} catch (Exception e) {
return "连接服务器失败" ;
}
}
}
感谢解答问题的码友
高洛峰2017-04-17 13:03:22
I guess it may be that the network access permission is not included in AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Update with the topic owner (*•̀ㅂ•́)و
Since network-related operations may be delayed, in order to avoid a bad user experience, they are usually not performed in the UI thread, but instead open a separate thread.
The simpler method is to use AsyncTask
. Here is an example from the official website:
public class HttpExampleActivity extends Activity {
private static final String DEBUG_TAG = "HttpExample";
private EditText urlText;
private TextView textView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
urlText = (EditText) findViewById(R.id.myUrl);
textView = (TextView) findViewById(R.id.myText);
}
// When user clicks button, calls AsyncTask.
// Before attempting to fetch the URL, makes sure that there is a network connection.
public void myClickHandler(View view) {
// Gets the URL from the UI's text field.
String stringUrl = urlText.getText().toString();
ConnectivityManager connMgr = (ConnectivityManager)
getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
new DownloadWebpageTask().execute(stringUrl);
} else {
textView.setText("No network connection available.");
}
}
// Uses AsyncTask to create a task away from the main UI thread. This task takes a
// URL string and uses it to create an HttpUrlConnection. Once the connection
// has been established, the AsyncTask downloads the contents of the webpage as
// an InputStream. Finally, the InputStream is converted into a string, which is
// displayed in the UI by the AsyncTask's onPostExecute method.
private class DownloadWebpageTask extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... urls) {
// params comes from the execute() call: params[0] is the url.
try {
return downloadUrl(urls[0]);
} catch (IOException e) {
return "Unable to retrieve web page. URL may be invalid.";
}
}
// onPostExecute displays the results of the AsyncTask.
@Override
protected void onPostExecute(String result) {
textView.setText(result);
}
}
...
}
Well, just create a AsyncTask
subclass instance in the event method and call its execute
method.
What is executed is doInBackgound
. After the sub-thread completes execution, onPostExecute
will be called to perform the final work.
怪我咯2017-04-17 13:03:22
It’s still unreasonable, it shouldn’t be so complicated! Unreasonable, it is recommended to use Android-async-http