Android
ʹÓÃHttpURLConnection
Ê×ÏÈ»ñÈ¡µ½Ê¹ÓÃHttpURLConnectionµÄʵÀý:new³öÒ»¸öUrl¶ÔÏó,²¢´«ÈëÄ¿±êµÄÍø·µØÖ·,È»ºóµ÷ÓÃurl.openConnection()·½·¨¼´¿É
URL url=new URL("http://www.baidu.com");
HttpURLConnection connection=(HttpURLConnection) url.openConnection();
»ñȡʵÀýÖ®ºó,ÎÒÃÇ¿ÉÒÔÉèÖÃÒ»ÏÂHTTPÇëÇóËùʹÓõķ½·¨,³£ÓõÄÖ÷Òª·½·¨:GETºÍPOST¡£GET±íʾϣÍû´Ó·þÎñÆ÷ÄÇÀï»ñÈ¡Êý¾Ý,¶øPOSTÔò±íʾϣÍûÌá½»Êý¾Ý¸ø·þÎñÆ÷¡£
д·¨ÈçÏÂ:
connection.setRequestMethod("GET");
È»ºó±ã¿ÉÒÔ½øÐÐЩ×ÔÓɶ¨ÖÆÁË,±ÈÈçÉèÖÃÁ¬½Ó³¬Ê±,¶ÁÈ¡³¬Ê±µÄºÁÃëÊý,ÒÔ¼°·þÎñÆ÷Ï£ÍûµÃµ½Ò»Ð©ÏûϢͷµÈ¡£×ÜÖ®Õⲿ·ÖÄÚÈݸù¾Ý×Ô¼ºµÄʵ¼ÊÇé¿ö½øÐбàд,ʾÀý:
connection.setconnectTimeout(8000);
connection.setReadTimeout(8000);
Ö®ºóÔÙµ÷ÓÃgetInputStream()·½·¨¾Í¿ÉÒÔ»ñÈ¡µ½·þÎñÆ÷·µ»ØµÄÊäÈëÁ÷ÁË,È»ºó¾ÍÊǶÔÊäÈëÁ÷¶ÁÈ¡ÁË¡£
InputStream in =connection.getInputStream();
×îºó¿ÉÒÔµôÓÃdisconnect()·½·¨½«Õâ¸öHTTPÁ¬½Ó¹Øµô
connection.disconnect();
ʾÀý:
package com.example.networktest;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
private static final String TAG = "MainActivity";
TextView responseText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.send_request).setOnClickListener(this);
responseText=findViewById(R.id.respose_text);
}
@Override
public void onClick(View v) {
if (v.getId()==R.id.send_request){
sendRequestWithHttpURLConnection();
Log.d(TAG, "onClick: 1");
}
}
private void sendRequestWithHttpURLConnection() {
new Thread(new Runnable() {
@Override
public void run() {
HttpURLConnection connection=null;
BufferedReader reader=null;
try {
URL url=new URL("http://www.baidu.com");
connection=(HttpURLConnection)url.openConnection();
connection.setRequestMethod("GET");
connection.setConnectTimeout(8000);
connection.setReadTimeout(8000);
InputStream in=connection.getInputStream();
reader =new BufferedReader(new InputStreamReader(in));
StringBuilder response=new StringBuilder();
String line;
while ((line=reader.readLine())!=null){
response.append(line);
}
showResponse(response.toString());
Log.d(TAG, "run: "+response.toString());
} catch (Exception e) {
e.printStackTrace();
}finally {
if(reader!=null){
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(connection!=null){
connection.disconnect();
}
}
}
}).start();
}
private void showResponse(String response) {
runOnUiThread(new Runnable() {
@Override
public void run() {
responseText.setText(response);
}
});
}
}
ʹÓÃOKHttp
OkHttpµÄÏîÄ¿Ö÷Ò³µØÖ·:https://github.com/square/okhttp
-
Ìí¼ÓÒÀÀµ: -
¾ßÌåÓ÷¨
´´½¨Ò»¸öOKHttPClientµÄʵÀý
OKHttClient client = new OKHttClient();
Èç¹ûÏë·¢ÆðÒ»ÌõHTTPÇëÇó,¾ÍÐèÒª´´½¨Ò»¸öRequest¶ÔÏó:
Request request =new Request.Builder().build();
ÉÏÊö´úÂëÖ»ÊÇ´´½¨ÁËÒ»¸ö¿ÕµÄRequest¶ÔÏó,²¢Ã»ÓÐʲôʵ¼Ê×÷ÓÃ,ÎÒÃÇ¿ÉÒÔÔÚ×îÖÕµÄbuild()·½·¨Ö®Ç°Á¬ ׺ ºÜ¶àÆäËû·½·¨À´·á¸»Õâ¸öRequest¶ÔÏó¡£±ÈÈç¿ÉÒÔͨ¹ýurl()·½·¨À´ÉèÖÃÄ¿±êµÄÍøÂçµØÖ·ÈçÏÂËùʾ:
Request request = new Request.Builder()
.url("http://www/baidu.com")
.build();
Ö®ºóµ÷ÓÃOKHttClientµÄnewCall()·½·¨À´´´½¨Ò»¸öCall¶ÔÏó,²¢µ÷ÓÃËüµÄexecute()·½·¨À´·¢ËÍÇëÇó²¢»ñÈ¡·þÎñÆ÷·µ»ØµÄÊý¾Ý,д·¨ÈçÏÂ:
Response response = client.newCall(request).execute();
ResponseÊÇ·þÎñÆ÷·µ»ØµÄÊý¾Ý,ÎÒÃÇ¿ÉÒÔÓÃÈçÏ·½·¨À´µÃµ½¾ßÌå·µ»ØµÄÄÚÈÝ:
String data =response.body().String();
PostÇëÇó:
//Ê×Ïȹ¹½¨³öÒ»¸öRequestBody¶ÔÏóÀ´´æ·ÅÌá½»µÄ²ÎÊý
RequestBody requestBody=new FormBody.Builder()
.add("username","admin")
.add("password","123456")
.build();
//ÔÚRequestÖе÷ÓÃpost()·½·¨²¢½«requestBody²ÎÊý´«Èë
Request request = new Request.Builder()
.url("http://www/baidu.com")
.post(requestBody)
.build();
//Ö®ºó²Ù×÷ºÍÉÏÃæÒ»ÑùÓÃexecute()·¢ËÍÇëÇó²¢»ñÈ¡·þÎñÆ÷·µ»ØµÄÊý¾Ý¼´¿É
ʾÀý:
...
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
private static final String TAG = "MainActivity";
TextView responseText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.send_request).setOnClickListener(this);
responseText=findViewById(R.id.respose_text);
}
@Override
public void onClick(View v) {
if (v.getId()==R.id.send_request){
// sendRequestWithHttpURLConnection();
sendRequestWithOKHttp();
Log.d(TAG, "onClick: 1");
}
}
private void sendRequestWithOKHttp() {
new Thread(() -> {
try {
OkHttpClient client=new OkHttpClient();
Request request=new Request.Builder().url("http://www.baidu.com").build();
Response response = client.newCall(request).execute();
String data= Objects.requireNonNull(response.body()).string();
showResponse(data);
}catch (IOException e) {
e.printStackTrace();
}
}).start();
}
private void showResponse(String response) {
runOnUiThread(() -> responseText.setText(response));
}
}
½âÎöxml
ʹÓÃTomacat´î½¨Ò»¸ö·þÎñÆ÷,ÔÚÕâ¸ö·þÎñÆ÷ÉÏÌṩһ¶ÎxmlÎı¾,È»ºóͨ¹ý³ÌÐò·ÃÎʲ¢½âÎö
ËùÒÔÎÒÃÇÔÚWebappsÀィһ¸öhtdosÎļþ¼Ð,ÔÙÔÚÕâ¸öÎļþ¼ÐÀィһ¸öget_data.xmlÎļþ¡£
<apps>
<app>
<id>1</id>
<name>牛�/name>
<version>1.0</version>
</app>
<app>
<id>1</id>
<name>牛逼邪�/name>
<version>2.0</version>
</app>
<app>
<id>1</id>
<name>牛逼邪神王</name>
<version>10.0</version>
</app>
</apps>
½âÎöxmlµÄ·½Ê½Óзdz£¶àÖÖ,±È½Ï³£ÓõÄÓÐpull½âÎöºÍSAX½âÎö
pull½âÎö:
¸ü¸Ä֮ǰ²¿·Ö´úÂë
...
private void sendRequestWithOKHttp() {
new Thread(() -> {
try {
.....
Request.Builder().url("http://10.0.2.2:8080/htdos/get_data.xml").build();
.....
parseXmlWithPull(data);
.....
}catch (IOException e) {
e.printStackTrace();
}
}).start();
}
...
private void parseXmlWithPull(String data) {
try{
XmlPullParserFactory factory=XmlPullParserFactory.newInstance();
XmlPullParser xmlPullParser=factory.newPullParser();
xmlPullParser.setInput(new StringReader(data));
int eventType=xmlPullParser.getEventType();
String id="";
String name="";
String version="";
while (eventType!=XmlPullParser.END_DOCUMENT){
String nodeName=xmlPullParser.getName();
switch (eventType){
case XmlPullParser.START_TAG:{
if ("id".equals(nodeName)){
id=xmlPullParser.nextText();
}else if("name".equals(nodeName)){
name=xmlPullParser.nextText();
}else if("version".equals(nodeName)){
version=xmlPullParser.nextText();
}
break;
}
case XmlPullParser.END_TAG:{
if ("app".equals(nodeName)){
Log.d(TAG, "id is "+id);
Log.d(TAG, "name is "+name);
Log.d(TAG, "version is "+version);
}
break;
}
default:
break;
}
eventType=xmlPullParser.next();
}
} catch (Exception e) {
e.printStackTrace();
}
}
...
SAX½âÎö
- н¨Ò»¸öÀà¼Ì³ÐDefaultHandler²¢ÖØд¸¸ÀàµÄÎå¸ö·½·¨
public class ContentHandler extends DefaultHandler {
private static final String TAG = "54";
String nodeName;
StringBuilder id;
StringBuilder name;
StringBuilder version;
@Override
public void endDocument() throws SAXException {
super.endDocument();
}
@Override
public void startDocument() throws SAXException {
id=new StringBuilder();
name=new StringBuilder();
version=new StringBuilder();
super.startDocument();
}
@Override
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
super.startElement(uri, localName, qName, attributes);
nodeName=localName;
}
@Override
public void endElement(String uri, String localName, String qName) throws SAXException {
super.endElement(uri, localName, qName);
if ("app".equals(localName)){
Log.d(TAG, "id is "+id.toString().trim());
Log.d(TAG, "name is "+name.toString().trim());
Log.d(TAG, "version is "+version.toString().trim());
id.setLength(0);
name.setLength(0);
version.setLength(0);
}
}
@Override
public void characters(char[] ch, int start, int length) throws SAXException {
super.characters(ch, start, length);
switch (nodeName){
case "id":
id.append(ch,start,length);
break;
case "name":
name.append(ch,start,length);
break;
case "version":
version.append(ch,start,length);
break;
default:
break;
}
}
}
ÐÞ¸ÄMainActivityÖдúÂë
...
private void parseXmlWithAX(String data) {
try {
SAXParserFactory factory=SAXParserFactory.newInstance();
XMLReader xmlReader = factory.newSAXParser().getXMLReader();
xmlReader.setContentHandler(new ContentHandler());
xmlReader.parse(new InputSource(new StringReader(data)));
} catch (SAXException | ParserConfigurationException | IOException e) {
e.printStackTrace();
}
}
½âÎöJOSN
ͬÀíÔÚhtdosÖд´½¨get_data.jsonÎļþ
[{"id":"5","version":"5.5","name":"Clans of Clans"},
{"id":"6","version":"7.0","name":"Boom Beach"},
{"id":"7","version":"3.5","name":"Clans Royale"}]
ʹÓÃJSONObject
...
private void sendRequestWithOKHttp() {
new Thread(() -> {
try {
.....
Request.Builder().url("http://10.0.2.2:8080/htdos/get_data.json").build();
.....
parseXmlWithPull(data);
.....
}catch (IOException e) {
e.printStackTrace();
}
}).start();
}
...
private void parseJsonWithJSONObject(String data) {
try{
JSONArray jsonArray=new JSONArray(data);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject object=jsonArray.getJSONObject(i);
String id=object.getString("id");
String name=object.getString("name");
String version=object.getString("version");
Log.d(TAG, "id is "+id);
Log.d(TAG, "name is "+name);
Log.d(TAG, "version is "+version);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
ÓÉÓÚÎÒÃÇÔÚ·þÎñÆ÷¶¨ÒåµÄÊÇÒ»¸öJSONÊý×é,Òò´ËÊ×ÏÈÊǽ«·µ»ØµÄÊý¾Ý´«Èëµ½ÁËÒ»¸öJSONArray¶ÔÏóÖС£È»ºóÑ»·±éÀúÕâ¸öJSONArray,´ÓÖÐÈ¡³öµÄÿһ¸öÔªËض¼ÊÇÒ»¸öJSONObject¶ÔÏó,ÿ¸öJSONObject¶ÔÏóÖÐÓÖ»á°üº¬id,nameºÍversionÕâЩÊý¾Ý,½Ó×ŵ÷ÓÃgetString()·½·¨½«ÕâЩÊý¾ÝÈ¡³ö´òÓ¡¡£
ʹÓÃGSON
GSONÊǹȸèÌṩµÄ¿ªÔ´¿â,ʹÓÃÇ°±ØÐëÔÚÏîÄ¿ÖÐÌí¼ÓGSON¿âµÄÒÀÀµ¡£ÔÚdependencies±Õ°üÏÂÌí¼Ó:
implementation 'com.google.code.gson:gson:2.8.6'
×îеİ汾ͨ¹ý¹ÙÍø²éѯ:
https://github.com/google/gson
GSON¿ÉÒÔ½«Ò»¶ÎJSON¸ñʽµÄ×Ö·û´®×Ô¶¯Ó³Éä³ÉÒ»¸ö¶ÔÏó,´Ó¶ø²»ÐèÒªÊÖ¶¯±àд´úÂë½øÐнâÎö¡£ Èç¹ûÒ»¶Îjson¸ñʽÈç:{¡°name¡±:¡±Tom¡±,¡±age¡±:¡±20¡±} ÄÇô¿ÉÒÔ¶¨ÒåÒ»¸öPersonÀà,¼ÓÈënameºÍageÁ½¸ö×Ö¶Î,È»ºóÖ»ÐèÒª¼òµ¥µ÷ÓÃÈçÏ´úÂë¾Í¿ÉÒÔ½«JSONÊý¾Ý×Ô¶¯½âÎöΪһ¸öPerson¶ÔÏó:
Gson gson = new Gson();
Person person = gson.fromJson(jsonData,Person.class);
Èç¹ûÐèÒª½âÎöµÄÊÇÊý×éµÄ»°»áÉÔ΢Âé·³µã,ÐèÒª½èÖúTypeToken½«ÆÚÍû½âÎö³ÉµÄÊý¾ÝÀàÐÍ´«Èëµ½fromJson()·½·¨ÖÐ:
List<Person> people = gson.fromJson(jsonData,new TypeToken<List<Person>>(){}.getType());
¿ª·¢Öеķâ×°
·¢ËÍHTTPÇëÇóµÄ´úÂë»ù±¾¶¼ÊÇÏàͬµÄ,ͨ³£ÔÚ¿ª·¢¹ý³ÌÖÐ,½«Í¨ÓõÄÍøÂç²Ù×÷ÌáÈ¡µ½Ò»¸ö¹«¹²µÄÀàÖÐ,±ÈÄã¸ßÌṩһ¸ö¾²Ì¬·½·¨,µ±ÏëÒª·¢ÆðÍøÂçÇëÇóµÄʱºò,Ö»ÐèÒª¼òµ¥µ÷ÓÃÒ»ÏÂÕâ¸ö·½·¨¼´¿É¡£¿ÉÒÔÏòÏÂÃæÄÇÑù:
public class HttpUtil {
public static void sendOkHttpRequest(String address, Callback callback){
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(address)
.build();
client.newCall(request).enqueue(callback);
}
}
²»ÊÇ֮ǰµ÷ÓÃexecute()·½·¨,¶øÊÇ×îºóµ÷ÓõÄenqueue()·½·¨¡£ÔÚÐèÒªÖ´ÐÐÇëÇóµÄʱºò:
1HttpUtil.sendOkHttpRequest("http://www.baidu.com", new Callback() {
@Override
public void onFailure(@NonNull Call call, @NonNull IOException e) {
//´¦ÀíÒì³£Çé¿ö
}
@Override
public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
//µÃµ½·þÎñÆ÷·µ»ØµÄ¾ßÌåÄÚÈÝ
String responseData = response.body().string();
}
});
ͨ¹ý»Øµ÷·½·¨µ½´ï´¦Àí·µ»ØÊý¾ÝµÄÄ¿µÄ¡£
¸ù¾Ý¹þà¶à¸µÂµÄÎÄÕÂÓÐËùÐÞ¸Ä:https://blog.csdn.net/YCF8746/article/details/117201088?spm=1001.2014.3001.5501
|