GVKun编程网logo

Apache http客户端或URLConnection(apache http服务器)

15

在本文中,我们将带你了解Apachehttp客户端或URLConnection在这篇文章中,我们将为您详细介绍Apachehttp客户端或URLConnection的方方面面,并解答apachehtt

在本文中,我们将带你了解Apache http客户端或URLConnection在这篇文章中,我们将为您详细介绍Apache http客户端或URLConnection的方方面面,并解答apache http服务器常见的疑惑,同时我们还将给您一些技巧,以帮助您实现更有效的apache http客户端org.apache.http.NoHttpResponseException:目标服务器无法响应、HttpURLConnection、HttpURLConnection (代码实现 http 请求)、HttpURLConnection Already connected异常

本文目录一览:

Apache http客户端或URLConnection(apache http服务器)

Apache http客户端或URLConnection(apache http服务器)

我需要在android应用程序上下载网页,并且很难决定是使用android apache http客户端还是使用Java的URLConnection。

有什么想法吗?

答案1

小编典典

对于大多数事情,我会说这HttpClient是要走的路。但是,在某些情况和极端情况下,我会退后一步URLConnection

编辑

我认为这HttpUrlConnection是更快的,因为它HttpClient是在标准Java库的基础上构建的。但是我会发现HttpClient代码更快,更容易编写和维护。根据下面的评论,的核心要素HttpClient已进行了性能优化。

如果性能是一个主要问题,那么最好的选择是编写两个客户端,每个使用一种方法,然后对它们进行基准测试。如果您这样做,请让我们知道结果。

apache http客户端org.apache.http.NoHttpResponseException:目标服务器无法响应

apache http客户端org.apache.http.NoHttpResponseException:目标服务器无法响应

我正在使用Apache HTTP客户端来testing我的WS。 我在运动衫上写了一个get WS。 这个WS的URL是

http://localhost:8080/mobilestore/rest/sysgestockmobilews/getinventory?xml=dataString

使用url调用这个WS我已经写了一个方法如下

public static void getInventory(String input) throws ClientProtocolException,IOException { System.out.println(input); String url = URL + "getinventory"; HttpClient client = new DefaultHttpClient(); List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1); nameValuePairs.add(new BasicNameValuePair("xml",input)); String paramString = URLEncodedUtils.format(nameValuePairs,"utf-8"); url += "?" + paramString; System.out.println(url); HttpGet request = new HttpGet(url); HttpResponse response = client.execute(request); BufferedReader rd = new BufferedReader(new InputStreamReader(response .getEntity().getContent())); String line = ""; while ((line = rd.readLine()) != null) { System.out.println(line); } }

现在,当我运行该程序,并通过url到这个function,我得到exception在线

HttpResponse response = client.execute(request);

例外情况如下

Ubuntu + PBS + Apache? 我如何显示一个正在运行的工作列表作为一个网站?

htaccessurl重写不工作

在归档opentokaudio/video聊天时遇到问题

如何跟踪PHP5-fpm的umask设置来自ubuntu

如何使用Apache POI从Excel电子表格获取图表信息?

Aug 14,2013 9:31:50 PM org.apache.http.impl.client.DefaultRequestDirector tryExecute INFO: I/O exception (org.apache.http.NoHttpResponseException) caught when processing request: The target server Failed to respond Aug 14,2013 9:31:50 PM org.apache.http.impl.client.DefaultRequestDirector tryExecute INFO: retrying request Aug 14,2013 9:31:50 PM org.apache.http.impl.client.DefaultRequestDirector tryExecute INFO: retrying request Exception in thread "main" org.apache.http.NoHttpResponseException: The target server Failed to respond at org.apache.http.impl.conn.DefaultHttpResponseParser.parseHead(DefaultHttpResponseParser.java:95) at org.apache.http.impl.conn.DefaultHttpResponseParser.parseHead(DefaultHttpResponseParser.java:62) at org.apache.http.impl.io.AbstractMessageParser.parse(AbstractMessageParser.java:254) at org.apache.http.impl.AbstractHttpClientConnection.receiveResponseHeader(AbstractHttpClientConnection.java:289) at org.apache.http.impl.conn.DefaultClientConnection.receiveResponseHeader(DefaultClientConnection.java:252) at org.apache.http.impl.conn.ManagedClientConnectionImpl.receiveResponseHeader(ManagedClientConnectionImpl.java:191) at org.apache.http.protocol.HttpRequestExecutor.doReceiveResponse(HttpRequestExecutor.java:300) at org.apache.http.protocol.HttpRequestExecutor.execute(HttpRequestExecutor.java:127) at org.apache.http.impl.client.DefaultRequestDirector.tryExecute(DefaultRequestDirector.java:715) at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:520) at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:906) at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:805) at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:784) at com.tainosystems.http.client.TestWs.getInventory(TestWs.java:66) at com.tainosystems.http.client.TestWs.main(TestWs.java:47)

现在,如果我使用的WSurl,并使用任何浏览器打它,我得到了预期的结果,但我想知道我的Apache HTTP客户端代码有什么问题..

在virtualenv django的Apache mod_wsgi错误

Internet Explorer 8 + Deflate

apache tomcat + apache httpd + mod_proxy + mod_rewrite +表单发布数据

防止执行父文件夹的.htaccess

什么是/ path /(null)请求的来源?

我经历了从这里的链接,得到了这个答案: 得到NoHttpResponseException负载测试

这使我走上正轨。 稍微更新答案就是使用当前http-client 4.5 API的解决方案:

private final HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(createHttpClient()); private CloseableHttpClient createHttpClient() { return HttpClients.custom().setRetryHandler((exception,executionCount,context) -> { if (executionCount > 3) { LOGGER.warn("Maximum tries reached for client http pool "); return false; } if (exception instanceof org.apache.http.NoHttpResponseException) { LOGGER.warn("No response from server on " + executionCount + " call"); return true; } return false; }).build(); }

我也在那里使用spring-web,所以我使用客户端作为RestTemplate工厂的参数,因为我希望它在RestTemplate中使用。

检查你的“URL”是否有正确的值。 错误消息显示“目标服务器无法响应”。 这是要么你提供的网址有错误或服务器已关闭。 如果您提供了错误的参数名称/值或其他内容,则错误消息会有所不同。

总结

以上是小编为你收集整理的apache http客户端org.apache.http.NoHttpResponseException:目标服务器无法响应全部内容。

如果觉得小编网站内容还不错,欢迎将小编网站推荐给好友。

HttpURLConnection

HttpURLConnection

package com.test;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.regex.Pattern;

/**
 * Http操作辅助工具
 * 
 */
public class HttpTool {
    /**
     * GET请求数据
     * 
     * @param get_url url地址
     * @param content key=value形式
     * @return 返回结果
     * @throws Exception
     */
    public String sendGetData(String get_url, String content) throws Exception {
        String result = "";
        URL getUrl = null;
        BufferedReader reader = null;
        String lines = "";
        HttpURLConnection connection = null;
        try {
            if (content != null && !content.equals(""))
                get_url = get_url + "?" + content;
            // get_url = get_url + "?" + URLEncoder.encode(content, "utf-8");
            getUrl = new URL(get_url);
            connection = (HttpURLConnection) getUrl.openConnection();
            connection.connect();
            // 取得输入流,并使用Reader读取
            reader = new BufferedReader(new InputStreamReader(
                    connection.getInputStream(), "utf-8"));// 设置编码
            while ((lines = reader.readLine()) != null) {
                result = result + lines;
            }
            return result;
        } catch (Exception e) {
            throw e;
        } finally {
            if (reader != null) {
                reader.close();
                reader = null;
            }
            connection.disconnect();
        }
    }

    /**
     * @param POST_URL url地址
     * @param content key=value形式
     * @return 返回结果
     * @throws Exception
     */
    public String sendPostData(String POST_URL, String content) throws Exception {
        HttpURLConnection connection = null;
        DataOutputStream out = null;
        BufferedReader reader = null;
        String line = "";
        String result = "";
        try {
            URL postUrl = new URL(POST_URL);
            connection = (HttpURLConnection) postUrl.openConnection();
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setRequestMethod("POST");
            // Post 请求不能使用缓存
            connection.setUseCaches(false);
            connection.setInstanceFollowRedirects(true);
            connection.setRequestProperty("Content-Type",
                    "application/x-www-form-urlencoded");
            connection.connect();

            out = new DataOutputStream(connection.getOutputStream());
            // content = URLEncoder.encode(content, "utf-8");
            // DataOutputStream.writeBytes将字符串中的16位的unicode字符�?8位的字符形式写道流里�?
            out.writeBytes(content);
            out.flush();
            out.close();
            // 获取结果
            reader = new BufferedReader(new InputStreamReader(
                    connection.getInputStream(), "utf-8"));// 设置编码
            while ((line = reader.readLine()) != null) {
                result = result + line;
            }
            return result;
        } catch (Exception e) {
            throw e;
        } finally {
            if (out != null) {
                out.close();
                out = null;
            }
            if (reader != null) {
                reader.close();
                reader = null;
            }
            connection.disconnect();
        }
    }

    /*
     * 过滤掉html里不安全的标签,不允许用户输入这些标签?
     */
    public static String htmlFilter(String inputString) {
        // return inputString;
        String htmlStr = inputString; // 含html标签的字符串
        String textStr = "";
        java.util.regex.Pattern p_script;
        java.util.regex.Matcher m_script;

        try {
            String regEx_script = "<[\\s]*?(script|style)[^>]*?>[\\s\\S]*?<[\\s]*?\\/[\\s]*?(script|style)[\\s]*?>";
            String regEx_onevent = "on[^\\s]+=\\s*";
            String regEx_hrefjs = "href=javascript:";
            String regEx_iframe = "<[\\s]*?(iframe|frameset)[^>]*?>[\\s\\S]*?<[\\s]*?\\/[\\s]*?(iframe|frameset)[\\s]*?>";
            String regEx_link = "<[\\s]*?link[^>]*?/>";

            htmlStr = Pattern.compile(regEx_script, Pattern.CASE_INSENSITIVE)
                    .matcher(htmlStr).replaceAll("");
            htmlStr = Pattern.compile(regEx_onevent, Pattern.CASE_INSENSITIVE)
                    .matcher(htmlStr).replaceAll("");
            htmlStr = Pattern.compile(regEx_hrefjs, Pattern.CASE_INSENSITIVE)
                    .matcher(htmlStr).replaceAll("");
            htmlStr = Pattern.compile(regEx_iframe, Pattern.CASE_INSENSITIVE)
                    .matcher(htmlStr).replaceAll("");
            htmlStr = Pattern.compile(regEx_link, Pattern.CASE_INSENSITIVE)
                    .matcher(htmlStr).replaceAll("");

            // p_html = Pattern.compile(regEx_html, Pattern.CASE_INSENSITIVE);
            // m_html = p_html.matcher(htmlStr);
            // htmlStr = m_html.replaceAll(""); // 过滤html标签

            textStr = htmlStr;

        } catch (Exception e) {
            System.err.println("Html2Text: " + e.getMessage());
        }

        return textStr;
    }

    public static void main(String args[]) {
        HttpTool t = new HttpTool();
        try {
            String ret = t.sendGetData("http://pinyin.sogou.com/dict/", "");
            System.out.println(ret);
            String ret_filter = htmlFilter(ret);
            System.out.println(ret_filter);
            String ret1 = t.sendPostData("http://pinyin.sogou.com/dict/", "");
            System.out.println(ret1);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

}


HttpURLConnection (代码实现 http 请求)

HttpURLConnection (代码实现 http 请求)

String reqUrl="www.baidu.com";
URL url=new URL(reqUrl);
    HttpURLConnection conn=(HttpURLConnection)url.openConnection();
    conn.setDoInput(true);
    conn.setDoOutput(true);
    conn.setUseCaches(false);
    conn.setRequestMethod("GET");//POST
// 如果为 Post 请求则要将数据提交
OutputStream os=conn.getOutputStream();
// 将要提交的数据写入 os 即可 (格式为 name=value&name2=value2). 不要忘记刷新
// 如果为 GET 请求则参数通过 reqUrl 传递
// 为防止中文乱码,最好是对提交的数据进行 UrlEncode 编码(对 get/post 请求都适用)
// 在提交请求之后,直接处理返回状态及结果即可。如下:
int code=conn.getResponseCode();
String message=conn.getResponseMessage();
if (code==200&&message.equals ("OK"))// 返回成功
{
InputStream is=conn.getInputStream();
}

HttpURLConnection Already connected异常

HttpURLConnection Already connected异常

小白又来提问题了,多方寻求无解 

正在做上传使用的是HttpURLConnection加sessionID上传用户数据

昨天上传还很正常,下午快下班了就出错,老夫心痛 T_T

上传代码如下:

public static void upload(String host,String sessionID,File file,Map<String,String> params,FileUploadListener listener){

        String BOUNDARY = UUID.randomUUID().toString(); //边界标识 随机生成 String PREFIX = "--" , LINE_END = "\r\n";
        String CONTENT_TYPE = "multipart/form-data"; //内容类型
        HttpURLConnection conn=null;
        //System.setProperty("http.keepAlive", "false");
        //System.setProperty("sun.net.http.allowRestrictedHeaders", "true");
        try {
            URL url = new URL(host);
            conn = (HttpURLConnection) url.openConnection();

            conn.setReadTimeout(TIME_OUT);
            conn.setConnectTimeout(TIME_OUT);
            conn.setRequestMethod("POST"); //请求方式
            conn.setRequestProperty("cookie",sessionID);
            conn.setRequestProperty("Charset", "utf-8");//设置编码
            conn.setRequestProperty("connection", "keep-alive");
            conn.setRequestProperty("Content-Type", CONTENT_TYPE + ";boundary=" + BOUNDARY);
            //conn.setDoInput(true); //允许输入流
            conn.setDoOutput(true); //允许输出流
            conn.setUseCaches(false); //不允许使用缓存

            if(file!=null) {
                /** * 当文件不为空,把文件包装并且上传 */
                OutputStream outputSteam=conn.getOutputStream();
                try {
                    DataOutputStream dos = new DataOutputStream(outputSteam);
                    conn.setChunkedStreamingMode(1024*100);
                    StringBuffer sb = new StringBuffer();
                    sb.append(LINE_END);

                    if(params!=null){//根据格式,开始拼接文本参数
                        for(Map.Entry<String,String> entry:params.entrySet()){
                            sb.append(PREFIX).append(BOUNDARY).append(LINE_END);//分界符
                            sb.append("Content-Disposition: form-data; name=\"" + entry.getKey() + "\"" + LINE_END);
                            sb.append("Content-Type: text/plain; charset=" + CHARSET + LINE_END);
                            sb.append("Content-Transfer-Encoding: 8bit" + LINE_END);
                            sb.append(LINE_END);
                            sb.append(entry.getValue());
                            sb.append(LINE_END);//换行!
                        }
                    }
                    sb.append(PREFIX);//开始拼接文件参数
                    sb.append(BOUNDARY); sb.append(LINE_END);

                    sb.append("Content-Disposition: form-data; name=\"coverpic\"; filename=\""+file.getName()+"\""+LINE_END);
                    sb.append(LINE_END);
                    //写入文件数据
                    dos.write(sb.toString().getBytes());
                    InputStream is = new FileInputStream(file);
                    byte[] bytes = new byte[1024];
                    long totalbytes = file.length();
                    long curbytes = 0;
                    Log.i("cky", "total=" + totalbytes);
                    int len = 0;
                    while((len=is.read(bytes))!=-1){
                        curbytes += len;
                        dos.write(bytes, 0, len);
                        listener.onProgress(curbytes, 1.0d * curbytes / totalbytes);
                    }
                    is.close();
                    dos.write(LINE_END.getBytes());//一定还有换行
                    byte[] end_data = (PREFIX+BOUNDARY+PREFIX+LINE_END).getBytes();
                    dos.write(end_data);
                    dos.flush();
                    /**
                     * 获取响应码 200=成功
                     * 当响应成功,获取响应的流
                     */
                    int code = conn.getResponseCode();

                    if (code == 200) {
                        InputStream iss = conn.getInputStream();
                        String state = getStringFromISS(iss);
                        listener.onFinish(state);
                    }
                }catch (Exception e) {
                    Log.e("test", "捕获异常 " + e.getMessage() + " | " + e.getLocalizedMessage());
                }

            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (conn != null) conn.disconnect();
        }

    }



在debug的时候显示:


参考 

http://stackoverflow.com/questions/23738940/httpurlconnection-java-lang-illegalstateexception-already-connected

关于Apache http客户端或URLConnectionapache http服务器的问题我们已经讲解完毕,感谢您的阅读,如果还想了解更多关于apache http客户端org.apache.http.NoHttpResponseException:目标服务器无法响应、HttpURLConnection、HttpURLConnection (代码实现 http 请求)、HttpURLConnection Already connected异常等相关内容,可以在本站寻找。

本文标签: