In android, HttpURLConnection and HttpClient implement data interaction between apps and PCs. androidhttpurl

Source: Internet
Author: User

In android, HttpURLConnection and HttpClient implement data interaction between apps and PCs. androidhttpurl

I have been studying android for a few days, but I am very satisfied. I feel very happy when I learn a little bit of knowledge. I think today is especially meaningful. Maybe this is an inexplicable love.

Next, let's talk about the differences between HttpURLConnection and HttpClient. In fact, both of them can perform data interaction between the client and the server, but the HttpClient encapsulation is more complete.

Let's take a look at the case first.

First, HttpURLConnection is used to access the server:

Client code:

  

Package com. example. demo01; import java. io. IOException; import java. io. outputStream; import java. io. printWriter; import java. io. unsupportedEncodingException; import java.net. httpURLConnection; import java.net. malformedURLException; import java.net. URL; import java.net. URLEncoder; import java. util. arrayList; import java. util. list; 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. 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 android. annotation. suppressLint; import android. app. activity; import android. OS. bundle; import android. OS. strictMode; import android. util. log; import android. view. menu; import android. view. view; import android. view. view. onClickListener; import android. widget. button; import android. widget. editText; import android. widget. toast; @ SuppressLint ("NewApi") public class MainActivity extends Activity {private EditText unameTxt, pwdTxt; private Button loginBtn; private static String serverPath = "http://tplovejava.xicp.net/uploadApp/HttpTestServlet "; @ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); // The StrictMode can be accessed when the mobile phone is installed. setThreadPolicy (new StrictMode. threadPolicy. builder (). detectDiskReads (). detectDiskWrites (). detectNetwork () // or. detectAll () for all detectable problems. penaltyLog (). build (); // The StrictMode can be accessed by mobile phone installation. setVmPolicy (new StrictMode. vmPolicy. builder (). detectLeakedSqlLiteObjects (). penaltyLog (). penaltyDeath (). build (); setContentView (R. layout. activity_main); unameTxt = (EditText) findViewById (R. id. user); pwdTxt = (EditText) findViewById (R. id. pasd); loginBtn = (Button) findViewById (R. id. submit); loginBtn. setOnClickListener (new OnClickListener () {@ Override public void onClick (View v) {String uname = unameTxt. getText (). toString (); String pwd = pwdTxt. getText (). toString (); // HttpURLConnection processes the interaction between the server and the client. try {URL url = new URL (serverPath); HttpURLConnection conn = (HttpURLConnection) url. openConnection (); // set the Input conn. setDoInput (true); // set the Output conn. setDoOutput (true); // sets the cache conn. setUseCaches (false); // set POST conn. setRequestMethod ("POST"); OutputStream OS = conn. getOutputStream (); PrintWriter pw = new PrintWriter (OS, true); pw. println (1245); // return the response success 200 int responseCode = conn. getResponseCode (); System. out. print (responseCode);} catch (MalformedURLException e) {e. printStackTrace ();} catch (IOException e) {// TODO Auto-generated catch block e. printStackTrace () ;}}) ;}@ Override public boolean onCreateOptionsMenu (Menu menu) {// Inflate the menu; this adds items to the action bar if it is present. getMenuInflater (). inflate (R. menu. main, menu); return true;} public String dealEncode (String str) {String encode = ""; try {encode = URLEncoder. encode (str, "UTF-8");} catch (UnsupportedEncodingException e) {e. printStackTrace ();} return encode ;}}

 

Type 2 HttpClient

HttpClient client = new DefaultHttpClient (); try {// set the parameter set List <NameValuePair> params = new ArrayList <NameValuePair> (); params. add (new BasicNameValuePair ("uname", uname); params. add (new BasicNameValuePair ("pwd", pwd); // post connection HttpPost httpPost = new HttpPost (serverPath); httpPost. setEntity (new UrlEncodedFormEntity (params, HTTP. UTF_8); HttpResponse response = client.exe cute (httpPost); if (response. getStatusLine (). getStatusCode () = HttpStatus. SC _ OK) {String str = EntityUtils. toString (response. getEntity (), "UTF-8"); Log. I ("info", str) ;}} catch (ClientProtocolException e) {e. printStackTrace ();} catch (IOException e) {// TODO Auto-generated catch block e. printStackTrace ();}

 

Server:

Protected void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {response. setCharacterEncoding ("UTF-8"); PrintWriter pw = response. getWriter (); String uname = request. getParameter ("uname"); String pwd = request. getParameter ("pwd");/* InputStream is = request. getInputStream (); InputStreamReader isr = new InputStreamReader (is); BufferedReader br = new BufferedReader (isr); System. out. println (br. readLine (); */if ("zs ". equals (uname) & "123 ". equals (pwd) {pw. print ("succeeded");} else {pw. print ("failed ");}}

 


Android uses HttpClient to access the network server and the client.

Answer: The preliminary judgment is that there is a problem with json parsing. In general, you must specify the content of the json string to parse json. In layman's terms, you need to know the structure of the entire json string. There are several braces {}, including nested braces {} and several braces [], including nested []. Then, the outer and inner layers must be braces {}, which is a json object, that is, JsonObject. Then, at this layer, check whether there are any brackets []. the json array is JsonArray. The Field Values of the current layer can be obtained based on the json object and field names of the current layer. In this case, move down a layer of json object, that is, view the second braces {}, and so on.

Android development and background data interaction

If the background Http can use HttpClient to submit the simulated get/post

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.