Tuesday, April 29, 2014

The most simple network communication failure, seeking reasons


Tablet Internet.
Android developers in learning. Want to try the most simple http traffic.

Now is running, the program will "Sorry, HttpGet has stopped running" Auto quit.
Ask you to help identify the error, or to run a successful and source http communications package!
Thank you!
This is part of the code, the following are the source package. What questions can go and see.
 
package com.example.aa;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
/ / Import android.content.DialogInterface.OnClickListener;

public class MainActivity extends Activity {
private TextView textView;
private Button get, post;
/ ** Called when the activity is first created. * /
@ Override
public void onCreate (Bundle savedInstanceState) {
super.onCreate (savedInstanceState);
setContentView (R.layout.activity_main);

textView = (TextView) findViewById (R.id.textView);
get = (Button) findViewById (R.id.get);
post = (Button) findViewById (R.id.post);

/ / Bind button listener
get.setOnClickListener (new OnClickListener () {
@ Override
public void onClick (View v) {
/ / Note: This can not be used ip 127.0.0.1 or localhost, Android emulator has its own as a localhost
Toast.makeText (MainActivity.this, "GET", Toast.LENGTH_LONG) show ();.
String uri = "http://192.168.0.101:80/";
textView.setText (get (uri));
}
});
/ / Bind button listener
post.setOnClickListener (new OnClickListener () {
@ Override
public void onClick (View v) {
Toast.makeText (MainActivity.this, "POST", Toast.LENGTH_LONG) show ();.
String uri = "http://192.168.0.101:80/";
textView.setText (post (uri));
}
});
}
/ **
* Send request to get access web
* @ Param uri web address
* @ Return response data
* /
private static String get (String uri) {
BufferedReader reader = null;
StringBuffer sb = null;
String result = "";
HttpClient client = new DefaultHttpClient ();
HttpGet request = new HttpGet (uri);
try {
/ / Send a request to obtain a response
HttpResponse response = client.execute (request);

/ / Request is successful
if (response.getStatusLine (). getStatusCode () == HttpStatus.SC_OK) {
reader = new BufferedReader (new InputStreamReader (response.getEntity () getContent ()).);
sb = new StringBuffer ();
String line = "";
String NL = System.getProperty ("line.separator");
while ((line = reader.readLine ())! = null) {
sb.append (line);
}
}
} Catch (ClientProtocolException e) {
e.printStackTrace ();
return "huai le!";
} Catch (IOException e) {
e.printStackTrace ();
return "huai le!";
}
finally {
try {
if (null! = reader) {
reader.close ();
reader = null;
}
} Catch (IOException e) {
e.printStackTrace ();
return "huai le!";
}
}
if (null! = sb) {
result = sb.toString ();
}

return result;
}
/ **
* Send a request to post, access web
* @ Param uri web address
* @ Return response data
* /
private static String post (String uri) {
BufferedReader reader = null;
StringBuffer sb = null;
String result = "";
HttpClient client = new DefaultHttpClient ();
HttpPost request = new HttpPost (uri);

/ / Save the parameters to be passed
List params = new ArrayList ();
/ / Add parameters
params.add (new BasicNameValuePair ("parameter", "send request to Post"));

try {
/ / Set the character set
HttpEntity entity = new UrlEncodedFormEntity (params, "utf-8");
/ / Request object
request.setEntity (entity);
/ / Send request
HttpResponse response = client.execute (request);

/ / Request is successful
if (response.getStatusLine (). getStatusCode () == HttpStatus.SC_OK) {
System.out.println ("post success");
reader = new BufferedReader (new InputStreamReader (response.getEntity () getContent ()).);
sb = new StringBuffer ();
String line = "";
String NL = System.getProperty ("line.separator");
while ((line = reader.readLine ())! = null) {
sb.append (line);
}
}
} Catch (ClientProtocolException e) {
e.printStackTrace ();
} Catch (IOException e) {
e.printStackTrace ();
}
finally {
try {
/ / Close the stream
if (null! = reader) {
reader.close ();
reader = null;
}
} Catch (IOException e) {
e.printStackTrace ();
}
}
if (null! = sb) {
result = sb.toString ();
}
return result;
}
}


This is my source, the package address:
http://pan.baidu.com/s/1jGE5kGY
<-! Main posts under Banner (D4) -><-! Posts under the main text (D5) ->
Reply:
Paste the error log. .
Reply:
cited a floor jiaqiangm reply:
paste error log. .

02-08 20:34:18.700: D / AndroidRuntime (1487): Shutting down VM
02-08 20:34:18.700: W / dalvikvm (1487): threadid = 1: thread exiting with uncaught exception (group = 0x41490930)
02-08 20:34:18.710: E / AndroidRuntime (1487): FATAL EXCEPTION: main
02-08 20:34:18.710: E / AndroidRuntime (1487): android.os.NetworkOnMainThreadException
02-08 20:34:18.710: E / AndroidRuntime (1487): at android.os.StrictMode $ AndroidBlockGuardPolicy.onNetwork (StrictMode.java: 1117)
02-08 20:34:18.710: E / AndroidRuntime (1487): at libcore.io.BlockGuardOs.connect (BlockGuardOs.java: 84)
02-08 20:34:18.710: E / AndroidRuntime (1487): at libcore.io.IoBridge.connectErrno (IoBridge.java: 127)
02-08 20:34:18.710: E / AndroidRuntime (1487): at libcore.io.IoBridge.connect (IoBridge.java: 112)
02-08 20:34:18.710: E / AndroidRuntime (1487): at java.net.PlainSocketImpl.connect (PlainSocketImpl.java: 192)
02-08 20:34:18.710: E / AndroidRuntime (1487): at java.net.PlainSocketImpl.connect (PlainSocketImpl.java: 459)
02-08 20:34:18.710: E / AndroidRuntime (1487): at java.net.Socket.connect (Socket.java: 842)
02-08 20:34:18.710: E / AndroidRuntime (1487): at org.apache.http.conn.scheme.PlainSocketFactory.connectSocket (PlainSocketFactory.java: 119)
02-08 20:34:18.710: E / AndroidRuntime (1487): at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection (DefaultClientConnectionOperator.java: 144)
02-08 20:34:18.710: E / AndroidRuntime (1487): at org.apache.http.impl.conn.AbstractPoolEntry.open (AbstractPoolEntry.java: 164)
02-08 20:34:18.710: E / AndroidRuntime (1487): at org.apache.http.impl.conn.AbstractPooledConnAdapter.open (AbstractPooledConnAdapter.java: 119)
02-08 20:34:18.710: E / AndroidRuntime (1487): at org.apache.http.impl.client.DefaultRequestDirector.execute (DefaultRequestDirector.java: 360)
02-08 20:34:18.710: E / AndroidRuntime (1487): at org.apache.http.impl.client.AbstractHttpClient.execute (AbstractHttpClient.java: 555)
02-08 20:34:18.710: E / AndroidRuntime (1487): at org.apache.http.impl.client.AbstractHttpClient.execute (AbstractHttpClient.java: 487)
02-08 20:34:18.710: E / AndroidRuntime (1487): at org.apache.http.impl.client.AbstractHttpClient.execute (AbstractHttpClient.java: 465)
02-08 20:34:18.710: E / AndroidRuntime (1487): at com.example.aa.MainActivity.get (MainActivity.java: 76)
02-08 20:34:18.710: E / AndroidRuntime (1487): at com.example.aa.MainActivity.access $ 1 (MainActivity.java: 68)
02-08 20:34:18.710: E / AndroidRuntime (1487): at com.example.aa.MainActivity $ 1.onClick (MainActivity.java: 50)
02-08 20:34:18.710: E / AndroidRuntime (1487): at android.view.View.performClick (View.java: 4204)
02-08 20:34:18.710: E / AndroidRuntime (1487): at android.view.View $ PerformClick.run (View.java: 17355)
02-08 20:34:18.710: E / AndroidRuntime (1487): at android.os.Handler.handleCallback (Handler.java: 725)
02-08 20:34:18.710: E / AndroidRuntime (1487): at android.os.Handler.dispatchMessage (Handler.java: 92)
02-08 20:34:18.710: E / AndroidRuntime (1487): at android.os.Looper.loop (Looper.java: 137)
02-08 20:34:18.710: E / AndroidRuntime (1487): at android.app.ActivityThread.main (ActivityThread.java: 5041)
02-08 20:34:18.710: E / AndroidRuntime (1487): at java.lang.reflect.Method.invokeNative (Native Method)
02-08 20:34:18.710: E / AndroidRuntime (1487): at java.lang.reflect.Method.invoke (Method.java: 511)
02-08 20:34:18.710: E / AndroidRuntime (1487): at com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run (ZygoteInit.java: 817)
02-08 20:34:18.710: E / AndroidRuntime (1487): at com.android.internal.os.ZygoteInit.main (ZygoteInit.java: 584)
02-08 20:34:18.710: E / AndroidRuntime (1487): at dalvik.system.NativeStart.main (Native Method)
02-08 20:34:18.710: D / dalvikvm (1487): GC_CONCURRENT freed 316K, 17% free 5482K/6528K, paused 2ms +3 ms, total 26ms
Reply:
logcat Lane
Reply:
at com.example.aa.MainActivity.get (MainActivity.java: 76)

See this line
Reply:
HttpResponse response = client.execute (request);
Reply:
references, 4th Floor jiaqiangm reply:
at com.example.aa.MainActivity.get (MainActivity.java: 76)

See this line

To solve: Android4.0 after network connection is not allowed in the main thread
behttp://www.2cto.com/kf/201310/248730.html
Reply:
This is very evident in the main thread for network operation caused. Create a new thread, the network operations carried out into this thread.
Reply:
android 4.0 or later to access the network, you must use a new thread
Reply:
reference to the 7th floor ltl451011 reply:
This is very evident in the main thread for network operation caused. Create a new thread, the network operations carried out into this thread.


reference to the 8th floor wangmin06jb reply:
android 4.0 or later to access the network, you must use the new thread

So I ask why I write or not?
I want to achieve and get access to the network function method of web content.
For example
 String httpget (String targetURL) {
.....
.....
.....
return response;
}



Reply:
I do not write a bit messy code posted up hope Daniel can give the code, thank you!
Reply:
 new Thread (new Runnable () {

@ Override
public void run () {
/ / Get method, handler throws a result
}
}) Start ();.

Reply:
some code android network connection can not be placed in the main ui thread! Comes with android AsyncTask class to complete the asynchronous operation, or the other from a Thread to handle.
Reply:
The main thread is not blocked more than 5 seconds, http requests and the like should be another open thread.

Reply:
reference to the 9th floor netseif reply:
Quote: references to the 7th floor ltl451011 reply:

This is very evident in the main thread for network operation caused. Create a new thread, the network operations carried out into this thread.


reference to the 8th floor wangmin06jb reply:
android 4.0 or later to access the network, you must use the new thread

So I ask why I write or not?
I want to achieve and get access to the network function method of web content.
For example
 String httpget (String targetURL) {
.....
.....
.....
return response;
}



You need this method into a new thread or HandlerThread execution. Or use AsyncTask, run doInBackgroud in.

No comments:

Post a Comment