郭霖大神第一行代码中关于POST请求的代码
栗几 2018-03-25 04:25:00 调试过程中发现POST请求中无法触发View控件,也郭霖的第一行代码里面也没给全POST请求的代码,查了诸多资料都没用相关解释,求大神解答
下面附上布局代码,和java类代码
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.okhttp.MainActivity">
<Button
android:id="@+id/register"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="注册"
/>
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/register_text"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</ScrollView>
Register.java
package com.example.okhttp;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class Register extends AppCompatActivity implements View.OnClickListener{
TextView registerText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button sendRegister=(Button)findViewById(R.id.register);
registerText=(TextView)findViewById(R.id.register_text);
sendRegister.setOnClickListener(this);
}
@Override
public void onClick(View v) {
if(v.getId()==R.id.register){
sendRequestWithHttpURLConnection();
}
}
private void sendRequestWithHttpURLConnection(){
new Thread(new Runnable() {
@Override
public void run() {
HttpURLConnection connection=null;
BufferedReader reader=null;
try{
URL url=new URL("http://www.qq.com");
connection=(HttpURLConnection)url.openConnection();
connection.setRequestMethod("POST");
DataOutputStream out=new DataOutputStream(connection.getOutputStream());
out.writeBytes ("userid=id&password=123&username=qxl");
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());
}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(final String response){
runOnUiThread(new Runnable() {
@Override
public void run() {
registerText.setText(response);
}
});
}
}