java-android安卓研发过程中urlconnection请求网址数据出现乱码如何解决?可以通过以下方法进行处理具体案例见下:
package org.tq.com;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class PostActivity extends Activity {
private Button but = null;
private EditText show = null;
private String baseUrl = "http://www.taaa.com/index.php";
HttpURLConnection urlConn = null;
URL url = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.main2);
but = (Button) this.findViewById(R.id.button2);
show = (EditText) this.findViewById(R.id.editText2);
but.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
try {
url = new URL(baseUrl);
urlConn = (HttpURLConnection) url.openConnection();
urlConn.setDoInput(true); //设置输入流采用字节流
urlConn.setDoOutput(true); //设置输出流采用字节流
urlConn.setRequestMethod("POST");
urlConn.setUseCaches(false); //设置缓存
urlConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
urlConn.setRequestProperty("Charset", "utf-8");
urlConn.connect();
DataOutputStream dos = new DataOutputStream(urlConn.getOutputStream());
dos.writeBytes("tqpadmac="+URLEncoder.encode("B407F9D67C80", "utf-8"));dos.writeBytes("tqpadver="+URLEncoder.encode("1", "utf-8"));
dos.flush();
dos.close();
//这句:new InputStreamReader(urlConn.getInputStream(), "gbk") 设置编码
BufferedReader br = new BufferedReader(new InputStreamReader(urlConn.getInputStream(),"gbk"));String line = "";
String result = "";
while(null != (line=br.readLine())){
result += line;
}
System.out.println("接到的数据: " + result);
show.setText(result);
br.close();
urlConn.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}
- 深圳市一键一家网络科技有限公司官方网址:http://www.songhu9.com.cn
- QQ:316675593,电话号码:19807655856
- 业务范围:公司网站建设、管理软件研发、软件网站二次开发、400电话、电商平台研发、公众号研发!
- 免责申明:本站内容均来源于网络,版权归原创所有,如有任何版权方面的问题,请与我们联系处理!