使用HttpURLConnection,请求结果乱码。

版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/qq_25925973/article/details/53371018


在使用网上一些HttpUtils,请求返回后,有中文,读取时发生乱码,使用
HttpClients
,以下是解决方法。


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.List;

import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import com.google.common.collect.Lists;

/**
 * Created by lihengjie on 2016/11/27.
 */
public class HttpClentT {

    public static String send(String url) {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        InputStream is = null;
        //封装请求参数
        List<NameValuePair> params = Lists.newArrayList();
        params.add(new BasicNameValuePair("cityEname", "henan"));
        String str = "";
        String result = "";
        try {
            //转换为键值对
            str = EntityUtils.toString(new UrlEncodedFormEntity(params, Consts.UTF_8));
            System.out.println(str);
            //创建Get请求
            HttpGet httpGet = new HttpGet(url + "?" + str);
            //执行Get请求,
            response = httpClient.execute(httpGet);
            //得到响应体
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                is = entity.getContent();
                //转换为字节输入流
                BufferedReader br = new BufferedReader(new InputStreamReader(is, Consts.UTF_8));
                String body = null;
                while ((body = br.readLine()) != null) {
                    result = body;
                }
            }
        } catch (ParseException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //关闭输入流,释放资源
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            //消耗实体内容
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            //关闭相应 丢弃http连接
            if (httpClient != null) {
                try {
                    httpClient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return result;
        }
    }
}



                                    
展开阅读全文

HttpURLConnection请求结果问题

12-01

请求两个地址,其中第一个可以返回结果,但第二个地址无结果,rn但http请求结果都是 url_con.getResponseCode()=200 就是打印不出来请求结果,郁闷中。。。rnrn这是为什么呢?rnrnrnpackage readXml;rnrnimport java.io.*;rnimport java.net.HttpURLConnection;rnimport java.net.MalformedURLException;rnimport java.net.ProtocolException;rnimport java.net.URL;rnimport java.net.URLConnection;rnimport java.util.*;rnimport org.dom4j.*;rnimport org.dom4j.io.*;rnrnpublic class ParseXML rnrn public static void main(String arge[]) throws Exception rn rn loadXml("http://wap.sonyericsson.com/UAprof/K700cR201.xml");rn loadXml("http://nds1.nds.nokia.com/uaprof/NN78-1r100.xml");rn loadXml("http://www.sohu.com");rn rn rn public static void loadXml(String xmlUrl) throws IOExceptionrn rn URL url = null;rn HttpURLConnection url_con = null;rn StringBuffer tempStr =null;rn FileWriter fw = null;rn// url = new URL(xmlUrl.replaceAll(" ", "%20"));rn url = new URL(xmlUrl);rn url_con = (HttpURLConnection) url.openConnection();rn url_con.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");rn url_con.setConnectTimeout(3000);rn url_con.setReadTimeout(3000);rn url_con.setRequestMethod("POST");rn url_con.setDoOutput(true);rn// url_con.getOutputStream().write(null);rn url_con.getOutputStream().flush();rn url_con.getOutputStream().close();rn url_con.getInputStream();rn rn System.out.println("----code:" + url_con.getResponseCode() );rn rn rn fw = new FileWriter("d:/temp/wap/cc.xml");rn InputStream in = url_con.getInputStream();rn BufferedReader rd = new BufferedReader(new InputStreamReader(in));rn tempStr = new StringBuffer();rn String inputLine=null;rn System.out.println("---------" + (rd.readLine()));rn System.out.println("---------" + (rd.read()));rn while ((inputLine = rd.readLine()) != null) rn rn if (inputLine.length() > 0)rn rn System.out.println("----code-sss------" + inputLine = rd.readLine());rn rn System.out.println("----code-------");rn tempStr.append(inputLine);rn tempStr.append("\n");rn rn rn rn if (url_con != null)rn rn url_con.disconnect();rn rn fw.write(tempStr.toString());rn fw.close();rn rd.close();rn int code = url_con.getResponseCode();rn rn System.out.println(tempStr.toString());rn System.out.println("----code:" + code);rn rn rn rn 论坛

HttpURLconnection请求无响应

09-16

这是一个普通的java测试类,测试可以打印出sessionIDrn[code=java]@Testrn public void test() rn String userName = "****";rn String password = "***rn OutputStream os;rn HttpURLConnection con;rn String sessionID = "";rn URL realUrl;rn try rn realUrl = new URL("http://seam.ustb.edu.cn:8080/jwgl/Login");rn con = (HttpURLConnection) realUrl.openConnection();rn //设置请求超时时间rn con.setReadTimeout(20000);rn con.setConnectTimeout(20000);rn // 设置POST方法rn con.setRequestMethod("POST");rn con.setUseCaches( false ); rn // 设置请求头rn con.setRequestProperty("Accept", "text/html");rn con.setRequestProperty("Connection", "keep-alive"); rn con.setInstanceFollowRedirects(false); // 禁止响应3**类型重定向rn // 设置允许输入输出流rn con.setDoInput(true);rn con.setDoOutput(true);rn String str = "username=" + userName + "&password=" + passwordrn + "&usertype=student";rn con.connect();rn os = con.getOutputStream();rn // 把提交数据以输出流的方式写到服务器rn os.write(str.getBytes());rn os.flush();rn os.close();rn con.disconnect();rn sessionID = con.getHeaderField("Set-Cookie");rn sessionID = sessionID.substring(0, sessionID.indexOf(";"));rn System.out.println(sessionID);rn catch (Exception e) rn e.printStackTrace();rn rn [/code]rn而同样一段代码放在androi应中时却无法访问,设置按钮点击事件,开启子线程进行登录验证,没有响应。rn这个是activityrn[code=java]@Overridern protected void onCreate(Bundle savedInstanceState) rn super.onCreate(savedInstanceState);rn setContentView(R.layout.activity_login);rn initData();rn login.setOnClickListener(new OnClickListener() rn rn public void onClick(View v) rn LoginAsyncTask l = new LoginAsyncTask();rn l.execute("41356021","zhRU19950804@");rn rn );rn rn private void initData() rn username = (EditText) findViewById(R.id.username);rn password = (EditText) findViewById(R.id.password);rn login = (Button) findViewById(R.id.Login);rn rn[/code]rn这个是验证登录线程rn[code=java]public class LoginAsyncTask extends AsyncTask rn @Overridern protected void onPreExecute() rn // TODO Auto-generated method stubrn super.onPreExecute();rn rn rn @Overridern protected String doInBackground(String... params) rn String userName = params[0];rn String password = params[1];rn OutputStream os;rn HttpURLConnection con;rn String sessionID = "";rn URL realUrl;rn try rn realUrl = new URL("http://seam.ustb.edu.cn:8080/jwgl/Login");rn con = (HttpURLConnection) realUrl.openConnection();rn //设置请求超时时间rn con.setReadTimeout(20000);rn con.setConnectTimeout(20000);rn // 设置POST方法rn con.setRequestMethod("POST");rn con.setUseCaches( false ); rn // 设置请求头rn con.setRequestProperty("Accept", "text/html");rn con.setRequestProperty("Connection", "keep-alive"); rn con.setInstanceFollowRedirects(false); // 禁止响应3**类型重定向rn // 设置允许输入输出流rn con.setDoInput(true);rn con.setDoOutput(true);rn String str = "username=" + userName + "&password=" + passwordrn + "&usertype=student";rn con.connect();rn os = con.getOutputStream();rn // 把提交数据以输出流的方式写到服务器rn os.write(str.getBytes());rn os.flush();rn os.close();rn con.disconnect();rn sessionID = con.getHeaderField("Set-Cookie");rn sessionID = sessionID.substring(0, sessionID.indexOf(";"));rn Log.e("s", sessionID);rn catch (Exception e) rn e.printStackTrace();rn rn return sessionID;rn rnrn[/code]rn这里的sessionID为null,求大神指导 论坛

没有更多推荐了,返回首页