郑州app开发时候,遇到使用httpurlconnection提交参数_get案例。下面是布局代码和java代码。
布局代码如下
下面是java代码
package cn.xhhkj.xhhkjtest;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private String path = "http://192.168.0.101/index/index/login";
private EditText et_username;
private EditText et_pwd;
private Button btn_login;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et_username = (EditText) findViewById(R.id.et_username);
et_pwd = (EditText) findViewById(R.id.et_password);
btn_login = (Button) findViewById(R.id.btn_login);
btn_login.setOnClickListener(this);
}
@Override
public void onClick(View v) {
if(v.getId()==R.id.btn_login){
new Thread(){
public void run() {
String username = et_username.getText().toString();
String pwd = et_pwd.getText().toString();
try {
String tempUrl = path+"?username="+ URLEncoder.encode(username, "utf-8")+"&password="+URLEncoder.encode(pwd, "utf-8");
URL url = new URL(tempUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setConnectTimeout(10000);
int code = connection.getResponseCode();
if(code==200){
InputStream inputStream = connection.getInputStream();
String result = Utils.getStringFromStream(inputStream);
showToast(result);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
};
}.start();
}
}
private void showToast(final String str){
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(getApplicationContext(), str, Toast.LENGTH_SHORT).show();
}
});
}
}
其中的Utils代码如下
package cn.xhhkj.xhhkjtest;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
public class Utils {
public static String getStringFromStream(InputStream inputStream) throws IOException {
ByteArrayOutputStream baso = new ByteArrayOutputStream();
int len = -1;
byte[] buffer = new byte[1024];
while((len = inputStream.read(buffer))!=-1){
baso.write(buffer, 0, len);
}
inputStream.close();
byte[] byteArray = baso.toByteArray();
return new String(byteArray);
}
}