Я пытаюсь получить информацию от моего сервера, поэтому я отправить запрос, чтобы получить ответ:Читайте входной поток onMainThreadException Android
private InputStream getInputStreamFromUrl(String url) {
InputStream content = null;
try {
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(new HttpGet(url));
content = response.getEntity().getContent();
} catch (Exception e) {
Log.v(TAG, "Network exception", e);
}
return content;
}
Я создаю задачу асинхронной подготовить мой запрос
public class HttpRequestTask extends AsyncTask<Request, Integer, Request[]>
{
HttpRequestTaskListner httpRequestTaskListner;
public void setHttpRequestTaskListner(HttpRequestTaskListner httpRequestTaskListner){
this.httpRequestTaskListner = httpRequestTaskListner;
}
protected Request[] doInBackground(Request...requests){
for(int i = 0; i<requests.length; i++){
requests[i].execute();
}
return requests;
}
protected void onPostExecute(Request[] requests){
if(requests != null){
httpRequestTaskListner.httpRequestTaskSuccess(requests);
}
else{
httpRequestTaskListner.HttpRequestTaskFailed();
}
}
public static interface HttpRequestTaskListner{
void httpRequestTaskSuccess(Request[] requests);
void HttpRequestTaskFailed();
}
}
и я исполню мой запрос
public void register(final ResultListner resultListner)
{
//define url
String url = webServiceUrl;
url += prop.getProperty("register");
//TODO change mobile id
url += "?mobile_id=test";
url += "&app_id="+prop.getProperty("applicationId");
//send request
Request request = new Request(url);
HttpRequestTask httpRequestTask = new HttpRequestTask();
httpRequestTask.setHttpRequestTaskListner(new HttpRequestTaskListner() {
@Override
public void httpRequestTaskSuccess(Request[] requests) {
resultListner.onResultSuccess(requests);
}
@Override
public void HttpRequestTaskFailed() {
resultListner.onResultFail();
}
});
httpRequestTask.execute(request);
}
Для завершения я использую код в моей деятельности
Server server = new Server(getApplicationContext());
server.register(new ResultListner() {
@Override
public void onResultSuccess(Request[] request) {
InputStream is = request[0].getResult();
String result = Util.getStringFromInputStream(is);
if(result.equals(Server.REGISTER_SUCCESS)){
System.out.println("aa");
}
else{
//TODO register error
}
}
@Override
public void onResultFail() {
// TODO fail request
}
});
А иногда я получил OnMainTheradException Но я не знаю, почему иногда это работает, и иногда я получил исключение это очень странно
Log:
08-24 17:00:35.630: E/AndroidRuntime(7265): FATAL EXCEPTION: main
08-24 17:00:35.630: E/AndroidRuntime(7265): android.os.NetworkOnMainThreadException
08-24 17:00:35.630: E/AndroidRuntime(7265): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1118)
08-24 17:00:35.630: E/AndroidRuntime(7265): at libcore.io.BlockGuardOs.recvfrom(BlockGuardOs.java:163)
08-24 17:00:35.630: E/AndroidRuntime(7265): at libcore.io.IoBridge.recvfrom(IoBridge.java:513)
08-24 17:00:35.630: E/AndroidRuntime(7265): at java.net.PlainSocketImpl.read(PlainSocketImpl.java:488)
08-24 17:00:35.630: E/AndroidRuntime(7265): at java.net.PlainSocketImpl.access$000(PlainSocketImpl.java:46)
08-24 17:00:35.630: E/AndroidRuntime(7265): at java.net.PlainSocketImpl$PlainSocketInputStream.read(PlainSocketImpl.java:240)
08-24 17:00:35.630: E/AndroidRuntime(7265): at org.apache.http.impl.io.AbstractSessionInputBuffer.fillBuffer(AbstractSessionInputBuffer.java:103)
08-24 17:00:35.630: E/AndroidRuntime(7265): at org.apache.http.impl.io.AbstractSessionInputBuffer.readLine(AbstractSessionInputBuffer.java:191)
08-24 17:00:35.630: E/AndroidRuntime(7265): at org.apache.http.impl.io.ChunkedInputStream.getChunkSize(ChunkedInputStream.java:220)
08-24 17:00:35.630: E/AndroidRuntime(7265): at org.apache.http.impl.io.ChunkedInputStream.nextChunk(ChunkedInputStream.java:183)
08-24 17:00:35.630: E/AndroidRuntime(7265): at org.apache.http.impl.io.ChunkedInputStream.read(ChunkedInputStream.java:155)
08-24 17:00:35.630: E/AndroidRuntime(7265): at org.apache.http.conn.EofSensorInputStream.read(EofSensorInputStream.java:159)
08-24 17:00:35.630: E/AndroidRuntime(7265): at java.io.InputStreamReader.read(InputStreamReader.java:244)
08-24 17:00:35.630: E/AndroidRuntime(7265): at java.io.Reader.read(Reader.java:145)
08-24 17:00:35.630: E/AndroidRuntime(7265): at java.io.Reader.read(Reader.java:258)
08-24 17:00:35.630: E/AndroidRuntime(7265): at java.util.Scanner.readMore(Scanner.java:2137)
08-24 17:00:35.630: E/AndroidRuntime(7265): at java.util.Scanner.findPostDelimiter(Scanner.java:2107)
08-24 17:00:35.630: E/AndroidRuntime(7265): at java.util.Scanner.setTokenRegion(Scanner.java:2017)
08-24 17:00:35.630: E/AndroidRuntime(7265): at java.util.Scanner.next(Scanner.java:1004)
08-24 17:00:35.630: E/AndroidRuntime(7265): at java.util.Scanner.next(Scanner.java:980)
08-24 17:00:35.630: E/AndroidRuntime(7265): at com.easyapp.util.Util.getStringFromInputStream(Util.java:27)
08-24 17:00:35.630: E/AndroidRuntime(7265): at com.easyapp.application.MainActivity$1.onResultSuccess(MainActivity.java:31)
08-24 17:00:35.630: E/AndroidRuntime(7265): at com.easyapp.server.Server$1.httpRequestTaskSuccess(Server.java:49)
08-24 17:00:35.630: E/AndroidRuntime(7265): at com.easyapp.server.HttpRequestTask.onPostExecute(HttpRequestTask.java:22)
08-24 17:00:35.630: E/AndroidRuntime(7265): at com.easyapp.server.HttpRequestTask.onPostExecute(HttpRequestTask.java:1)
08-24 17:00:35.630: E/AndroidRuntime(7265): at android.os.AsyncTask.finish(AsyncTask.java:631)
08-24 17:00:35.630: E/AndroidRuntime(7265): at android.os.AsyncTask.access$600(AsyncTask.java:177)
08-24 17:00:35.630: E/AndroidRuntime(7265): at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
08-24 17:00:35.630: E/AndroidRuntime(7265): at android.os.Handler.dispatchMessage(Handler.java:99)
08-24 17:00:35.630: E/AndroidRuntime(7265): at android.os.Looper.loop(Looper.java:137)
08-24 17:00:35.630: E/AndroidRuntime(7265): at android.app.ActivityThread.main(ActivityThread.java:4895)
08-24 17:00:35.630: E/AndroidRuntime(7265): at java.lang.reflect.Method.invokeNative(Native Method)
08-24 17:00:35.630: E/AndroidRuntime(7265): at java.lang.reflect.Method.invoke(Method.java:511)
08-24 17:00:35.630: E/AndroidRuntime(7265): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:994)
08-24 17:00:35.630: E/AndroidRuntime(7265): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:761)
08-24 17:00:35.630: E/AndroidRuntime(7265): at dalvik.system.NativeStart.main(Native Method)
Ошибка Util. Java на линии 27 является
public static String getStringFromInputStream(InputStream is)
{
if(is == null){
return null;
}
return new Scanner(is,"UTF-8").useDelimiter("\\A").next();
}
на
return new Scanner(is,"UTF-8").useDelimiter("\\A").next();
Правильно ли вы настроили резистор на сервере? – Piyush
Я просто получаю простой результат с сервера 0 или 1 – Ajouve
Хорошо ... так что это не проблема. вы получили правильный и идеальный ответ. Не так ли? – Piyush