Android sends http request to connect to the web to get data

1. Create a new Android project (I use AndroidStudio here, but I use eclipse in the learning stage, the code is the same).
2. Adding two permissions in AndroidManifest.xml configuration is enough. Many people on the Internet have configured a lot of permissions, and it is not useless in the future. If you want to send http requests, you only need to configure these two.
Insert picture description here
3. UI interface (activity_main.xml)

<TextView
        android:id="@+id/tv_json"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text=""
        />

4.java class (MainActivity.java)

package tgc.rj.qmkh;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import tgc.rj.qmkh.utils.FilesUtils;

public class MainActivity extends AppCompatActivity {
    private String urlWww="";//这里写你的请求web端的地址,比如http://192.168.1.2:8080/tsgl/android/bookAll
    private String response = "";
    private TextView tv_json;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tv_json = findViewById(R.id.tv_json);
        String par = "str="+"1323123";
        sendHttp(urlWww, par);//第一个是请求地址。第二个参数传的值。第二个参数如果没有参数,可以不带参数,直接给""
    }

    private void sendHttp(final String urlStr, final String paramStr){
        new Thread(new Runnable() {
            @Override
            public void run() {
                HttpURLConnection conn = null;
                try {
                    URL url = new URL(urlStr);
                    conn = (HttpURLConnection) url.openConnection();
                    conn.setRequestProperty("Charset", "UTF-8");
                    conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                    conn.setRequestMethod("POST");
                    conn.setConnectTimeout(8000);
                    conn.setReadTimeout(8000);
                    String param = paramStr;
                    OutputStream outputStream = conn.getOutputStream();
                    DataOutputStream out = new DataOutputStream(outputStream);
                    out.writeBytes(param);
                    out.flush();
                    out.close();
                    InputStream inputStream = conn.getInputStream();
                    //FilesUtils输入流输出流类(response是响应过来的数据)
                    response = FilesUtils.readInfo(inputStream);
                    runOnUiThread(new Runnable() {
                        public void run() {
                       		 //用runOnUiThread接收输出显示结果
                            tv_json.setText(response);
                        }
                    });
                    if (conn != null) {
                        conn.disconnect();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
}

5.FilesUtils.java (input stream output stream class)

public class FilesUtils {
    public static void saveInfo(OutputStream outputStream, String wenjian){
        try {
            outputStream.write(wenjian.getBytes());
            outputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static String readInfo(InputStream input) {
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len;
        try {
            while ((len = input.read(buffer))!=-1) {
                os.write(buffer, 0, len);
            }
            byte[] data = os.toByteArray();
            os.close();
            input.close();
            String str = new String(data);
            return str;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}

6. Web side
Please note that I passed a value of str = 1323123 in mainActivity.java, the following describes how to receive on the web side.
It's actually simple.

@Autowired
private BookService bookService;

@RequestMapping("/bookAll")
@ResponseBody
public Object bookAll(String str) {
	System.out.println("Android端传过来的值:"+str);
	List<Books> list = bookService.findAll();
	return list;
}

Effect picture:
Insert picture description here7. In the web code, as you have already seen, I returned a List to the Android side. In the Android side MainActivity.java runOnUiThread thread, I also received a response. This response is the value received on the web side. Also used a tv_json.setText (reponse); displayed on the interface. Please see the displayed effect.
Insert picture description here
If it is a list, it is actually json data, which needs to be processed. If it is an ordinary string, it can be used directly.

Thank you for your support. Learn it industry plus v together: zzaizhangzeng

Published 23 original articles · Like 11 · Visits 30,000+

Guess you like

Origin blog.csdn.net/weixin_42279584/article/details/93733567