GVKun编程网logo

如何通过Apache的HttpClient在Couchdb中设置pipe理员(给出一个curl的例子)(apache怎么调用php的)

25

本文将为您提供关于如何通过Apache的HttpClient在Couchdb中设置pipe理员的详细介绍,我们还将为您解释给出一个curl的例子的相关知识,同时,我们还将为您提供关于ApacheHtt

本文将为您提供关于如何通过Apache的HttpClient在Couchdb中设置pipe理员的详细介绍,我们还将为您解释给出一个curl的例子的相关知识,同时,我们还将为您提供关于Apache HttpClient 4.1-代理设置、apache HttpClient 学习系列--2 之HttpContext、Apache HttpClient在macOS上因Java 11失败、Apache HttpComponents:org.apache.http.client.ClientProtocolException的实用信息。

本文目录一览:

如何通过Apache的HttpClient在Couchdb中设置pipe理员(给出一个curl的例子)(apache怎么调用php的)

如何通过Apache的HttpClient在Couchdb中设置pipe理员(给出一个curl的例子)(apache怎么调用php的)

因此,我正在研究一个CouchDB Gui工具箱,以便于在Android上维护一个设置CouchDB的工作,因为在一个小型的移动设备上,Futon相当不舒服。

我想坚持“org.apache.http.client。*”包,这是工作得很好,直到我想设置pipe理员..

命令行工具“curl”就像一个魅力:

curl -X PUT http://127.0.0.1:5984/_config/admins/username -d ''"password"''

但是我一直把这个问题翻译成一个“org.apache.http.client.methods.HttpPut()”的方法。

任何帮助赞赏。

DefaultHttpClient client = new DefaultHttpClient(); HttpPut put = new HttpPut("http://127.0.0.1:5984/_config/admins/username"); put.setEntity(new StringEntity(""password"")); client.execute(put);

对,对不起。 只是为了完成答案,下面是如何处理我得到的请求的响应:

DefaultHttpClient client = new DefaultHttpClient(); JSONObject json = null; HttpPut put = new HttpPut("http://127.0.0.1:5984/_config/admins/username"); try { StringEntity strEntity = new StringEntity(""" + password + """); put.setEntity(strEntity); response = client.execute(put); httpentity responseEntity = response.getEntity(); //Or do something with the entity of the response // if (response.getStatusLine().getStatusCode() == 200) { // return something; // } } catch (UnsupportedEncodingException e) { e.printstacktrace(); } catch (IOException e) { e.printstacktrace(); }

总结

以上是小编为你收集整理的如何通过Apache的HttpClient在Couchdb中设置pipe理员(给出一个curl的例子)全部内容。

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

Apache HttpClient 4.1-代理设置

Apache HttpClient 4.1-代理设置

我正在尝试将一些参数发布到服务器,但是我需要设置代理。您可以帮助我对代码的“设置代理”部分进行排序吗?

HttpHost proxy = new HttpHost("xx.x.x.xx");

DefaultHttpClient httpclient = new DefaultHttpClient();

httpclient.getParams().setParameter("3128",proxy);


HttpPost httpost = new HttpPost(url);
List<NameValuePair> nvps = new ArrayList<NameValuePair>();

nvps.add(new BasicNameValuePair("aranan",song));

httpost.setEntity(new UrlEncodedFormEntity(nvps,HTTP.UTF_8));

HttpResponse response = httpclient.execute(httpost);
HttpEntity entity = response.getEntity();
System.out.println("Request Handled?: " + response.getStatusLine());

in = entity.getContent();

httpclient.getConnectionManager().shutdown();

apache HttpClient 学习系列--2 之HttpContext

apache HttpClient 学习系列--2 之HttpContext

首先是一个Servlet用于本次试验。

package com.lu.controller;

import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@SuppressWarnings("serial")
public class RirectServlet extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        this.doPost(request, response);
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=utf-8");

        OutputStream out = response.getOutputStream();
        PrintWriter pw = new PrintWriter(out);

        // 记录返回的内容
        String returnContent = null;

        HttpSession session = request.getSession();
        String user = (String) session.getAttribute("username");

        // 如果不为空,说明已登录
        if (user != null) {
            returnContent = "you have been logined, " + user;
        } else {
            // 为空说明未登录,设置username到session中
            String username = request.getParameter("username");
            session.setAttribute("username", username);
            returnContent = "login success";
        }

        try {
            pw.println(returnContent);
        } finally {
            pw.close();
            out.close();
        }
    }

}

在本机中访问URI为:http://localhost:8080/spiderweb/RirectServlet

下面看请求

package com.lu.test;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
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.client.methods.HttpPost;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;

public class HttpClientTest {

    private static HttpContext localContext = new BasicHttpContext();
    private static HttpClientContext context = HttpClientContext
            .adapt(localContext);

    public static void main(String[] args) throws Exception {
        CloseableHttpClient httpClient = HttpClients.createDefault();

        try {
            // 模拟表单
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("username", "**"));
            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params,
                    "UTF-8");
            HttpPost httpPost = new HttpPost(
                    "http://localhost:8080/spiderweb/RirectServlet");
            httpPost.setEntity(entity);

            // 将HttpClientContext传入execute()中
            CloseableHttpResponse response = httpClient.execute(httpPost,
                    context);

            try {
                HttpEntity responseEntity = response.getEntity();
                System.out.println(EntityUtils.toString(responseEntity));

            } finally {
                response.close();
            }
        } finally {
            httpClient.close();
        }

        CloseableHttpClient httpClient2 = HttpClients.createDefault();

        try {
            HttpGet httpGet = new HttpGet(
                    "http://localhost:8080/spiderweb/RirectServlet");

            // 设置相同的HttpClientContext
            CloseableHttpResponse response = httpClient2.execute(httpGet,
                    context);
            try {
                HttpEntity entity = response.getEntity();
                System.out.println(EntityUtils.toString(entity));
            } finally {
                response.close();
            }
        } finally {
            httpClient2.close();
        }

    }
}

输出结果为:

login success
you have been logined, **


可能大家认为这个结果很正常。第一次登陆了,第二次肯定会输出you have been logined, **。但是大家别忘了,现在不是在浏览器环境下,浏览器会帮你提取服务器传回的sessionId并在你下次请求的时候传给服务器,那么两次请求用的就是同一个session对象,那么自然的就会有上面的输出。

但是现在是在自己写代码访问。我们没有获取sessionId,也没有向服务器传送sessionId,那么两次请求服务器就会为你创建两个sessionId不同的session对象。

那为什么输出结果却是跟浏览器得到的结果一样呢?肯定是什么东西为我们自动完成了获取sessionId传送sessionId的功能。毫无疑问,就是context。 BasicHttpContext里有个Map<Object,Object>的对象用来记录一次请求响应的信息,当响应信息返回时,就会被set到context里,当然响应的cookie信息也就被存储在context里,包括传回的sessionId。

当第二次请求的时候传入相同的context,那么请求的过程中会将context里的sessionId提取出来传给服务器,sessionId一样,自然而然的就是同一个session对象。
那么大家明白context的作用了吗?
按照官方教程的说法来说

代表一个逻辑相关的会话的多个请求序列应该具有相同的HttpContext实例以确保请求之间的信息状态的自动传播



由于初学,不对的地方还望大家指出。

Apache HttpClient在macOS上因Java 11失败

Apache HttpClient在macOS上因Java 11失败

我正在尝试将我的代码从Java 8迁移到Java 11,此代码…

 private static String  readMultiHttpsUrlResultAsString(List<String> mbRecordingIds, String level) throws Exception{    String result = "";    class NaiveTrustStrategy implements TrustStrategy    {        @Override        public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException        {            return true;        }    };    SSLContext sslcontext = org.apache.http.ssl.SSLContexts.custom()            .loadTrustMaterial(new NaiveTrustStrategy())            .build();    CloseableHttpClient httpclient = HttpClients.custom()            .setSSLSocketFactory(new SSLConnectionSocketFactory(sslcontext))            .build();    StringBuilder sb = new StringBuilder("?recording_ids=");    for(String next:mbRecordingIds)    {        sb.append(next + ";");    }    sb.setLength(sb.length() - 1);    try    {        String url = "https://acousticbrainz.org/api/v1"+level+sb;        HttpGet httpget = new HttpGet(url);        try (CloseableHttpResponse response = httpclient.execute(httpget);)        {            int statusCode = response.getStatusLine().getStatusCode();            if(statusCode!=HttpURLConnection.HTTP_OK)            {                return "";            }            HttpEntity entity = response.getEntity();            result = EntityUtils.toString(entity);            EntityUtils.consume(entity);        }    }    finally    {        httpclient.close();    }    return result;}

}

在MacOS上使用(AdoptOpenJdk)Java 11.0.6失败了,

SSLContext sslcontext = org.apache.http.ssl.SSLContexts.custom()            .loadTrustMaterial(new NaiveTrustStrategy())            .build();

它可以在Windows上正常运行(也使用AdoptOpenJdk Java
11.0.6)。一个区别是Windows版本使用从带有jlink的jdk构建的cutdown jre,而MacOS版本使用AdoptOpenJDk
jre构建。MacOS版本是使用InfiniteKinds分支创建的AppBundler

这是堆栈跟踪:

java.lang.NoClassDefFoundError: Could not initialize class sun.security.ssl.SSLContextImpl$TLSContext    at java.base/java.lang.Class.forName0(Native Method)    at java.base/java.lang.Class.forName(Class.java:315)    at java.base/java.security.Provider$Service.getImplClass(Provider.java:1848)    at java.base/java.security.Provider$Service.newInstance(Provider.java:1824)    at java.base/sun.security.jca.GetInstance.getInstance(GetInstance.java:236)    at java.base/sun.security.jca.GetInstance.getInstance(GetInstance.java:164)    at java.base/javax.net.ssl.SSLContext.getInstance(SSLContext.java:168)    at org.apache.http.ssl.SSLContextBuilder.build(SSLContextBuilder.java:269)    at com.jthink.songkong.analyse.acousticbrainz.AcousticBrainz.readMultiHttpsUrlResultAsString(AcousticBrainz.java:409)    at com.jthink.songkong.analyse.acousticbrainz.AcousticBrainz.readLowLevelData(AcousticBrainz.java:373)

我正在使用Apache Httpclient 4.5.3,并且正在使用此lib,因为我是从需要使用ssl的Web服务获取数据的。

更新
我从下面的答案中将示例测试添加到了我的源代码中,并修改了我的构建,以使其在运行应用程序时成为开始类,并为我提供了该堆栈跟踪信息(当从命令行open使用内嵌的Java运行时运行捆绑软件时)由infinitekind
appbundler提供的捆绑包)

Exception in thread "main" java.lang.ExceptionInInitializerError    at java.base/javax.crypto.Cipher.getInstance(Unknown Source)    at java.base/sun.security.ssl.JsseJce.getCipher(Unknown Source)    at java.base/sun.security.ssl.SSLCipher.isTransformationAvailable(Unknown Source)    at java.base/sun.security.ssl.SSLCipher.<init>(Unknown Source)    at java.base/sun.security.ssl.SSLCipher.<clinit>(Unknown Source)    at java.base/sun.security.ssl.CipherSuite.<clinit>(Unknown Source)    at java.base/sun.security.ssl.SSLContextImpl.getApplicableSupportedCipherSuites(Unknown Source)    at java.base/sun.security.ssl.SSLContextImpl$AbstractTLSContext.<clinit>(Unknown Source)    at java.base/java.lang.Class.forName0(Native Method)    at java.base/java.lang.Class.forName(Unknown Source)    at java.base/java.security.Provider$Service.getImplClass(Unknown Source)    at java.base/java.security.Provider$Service.newInstance(Unknown Source)    at java.base/sun.security.jca.GetInstance.getInstance(Unknown Source)    at java.base/sun.security.jca.GetInstance.getInstance(Unknown Source)    at java.base/javax.net.ssl.SSLContext.getInstance(Unknown Source)    at org.apache.http.ssl.SSLContextBuilder.build(SSLContextBuilder.java:389)    at Example.main(Example.java:23)Caused by: java.lang.SecurityException: Can not initialize cryptographic mechanism    at java.base/javax.crypto.JceSecurity.<clinit>(Unknown Source)    ... 17 moreCaused by: java.lang.SecurityException: Can''t read cryptographic policy directory: unlimited    at java.base/javax.crypto.JceSecurity.setupJurisdictionPolicies(Unknown Source)    at java.base/javax.crypto.JceSecurity$1.run(Unknown Source)    at java.base/javax.crypto.JceSecurity$1.run(Unknown Source)    at java.base/java.security.AccessController.doPrivileged(Native Method)    ... 18 more

这与我以前有过不同,但是也许这是根本原因还是这种误导?

而如果我只是运行java -jar songkong6.9.jar它,那么它将运行Example并打印出 Loaded 没有错误,如果我从/
Library / Java指定完整路径,则它在所有情况下都适用(Java 11 / Java 14 / JDk和JRE)

更新 根据以下答案,我已经取得了一些进展。

安装在MacOS上的JRE包含一个conf文件夹,当使用InfiniteKinds
appbundler将JRE添加到我的捆绑包(SongKong)中时,它没有conf文件夹。它确实有一个lib /
security文件夹,其中包含,default.policy但这似乎还不够。

pauls-Mac-mini:Home paul$ ls -lR lib/securitytotal 704-rw-r--r--  1 paul  admin    1253 22 Apr 14:56 blacklisted.certs-rw-r--r--  1 paul  admin  103147 22 Apr 14:56 cacerts-rw-r--r--  1 paul  admin    8979 22 Apr 16:01 default.policy-rw-r--r--  1 paul  admin  233897 22 Apr 14:56 public_suffix_list.dat

安装构建的捆绑包后,如果我手动将conf文件夹从已安装的JRE复制到Java插件的Home文件夹中

例如

/Applications/SongKong.app/Contents/PlugIns/adoptopenjdk-11.jre/Contents/Home

位置,则示例代码和我的原始代码在从bundle中运行时都不会出现错误。

此外,似乎要查找的是无限文件夹及其内容(两个文件实际上是相同的),因此,如果我删除了几个文件,则剩下的就是

pauls-Mac-mini:Home paul$ pwd/Applications/SongKong.app/Contents/PlugIns/adoptopenjdk-11.jre/Contents/Homepauls-Mac-mini:Home paul$ ls -lR conftotal 0drwxr-xr-x  3 paul  admin  96 22 Apr 15:14 securityconf/security:total 0drwxr-xr-x  3 paul  admin  96 22 Apr 15:22 policyconf/security/policy:total 0drwxr-xr-x  4 paul  admin  128 22 Apr 15:28 unlimitedconf/security/policy/unlimited:total 16-rw-r--r--  1 paul  admin  146 22 Apr 15:06 default_US_export.policy-rw-r--r--  1 paul  admin  193 22 Apr 15:06 default_local.policy

然后它继续工作。

问题(除了为什么它不能开箱即用之外)是我认为我无法将文件复制到经过硬化的运行时应用程序的此位置,因此我需要将这些策略文件存储在其他位置,以便可以将其作为appbundler构建的一部分进行安装。因此,作为测试,我已重命名conf文件conf.old夹folder并将以下参数添加到捆绑包中

<string>-Djava.security.policy=/Applications/SongKong.app/Contents/PlugIns/adoptopenjdk-11.jre/Contents/Home/conf.old/security/policy/unlimited/default_local.policy</string>

或替换而不是附加策略文件

<string>-Djava.security.policy==/Applications/SongKong.app/Contents/PlugIns/adoptopenjdk-11.jre/Contents/Home/conf.old/security/policy/unlimited/default_local.policy</string>

但这是行不通的,我尝试了各种值,但没有任何效果。唯一有效的方法是将其保留在conf子文件夹中,然后不管是否传递此参数都无关紧要。(我也尝试添加-Dsecurity.manager作为另一个选项,但这只是导致有关日志记录权限的新错误。)

答案1

小编典典

最终,在Anish的帮助下,解决了缺少策略文件的问题,而这仅仅是使用AppBunder构建的包的问题。

jdk代码似乎真的希望conf在JRE中有一个文件夹,OpenJDk中有一个文件夹,但没有一次与AppBundler捆绑到我的应用程序中。因此,我下载了最新的AppBundler
src代码并对其进行了重建,然后重新构建了我的appbundle,并对其进行了修复,现在包含conf文件夹,并且应用程序运行时没有错误。

Apache HttpComponents:org.apache.http.client.ClientProtocolException

Apache HttpComponents:org.apache.http.client.ClientProtocolException

因此,我使用apache
HttpComponents处理Java中的http请求。现在,我想重用DefaultHttpClient,根据此示例,应该可以:http
://wiki.apache.org/HttpComponents/QuickStart
。该示例本身给出了ssl错误,因此我对其进行了简化和简化。现在我总是得到一个org.apache.http.client.ClientProtocolException

这是我的示例程序,基本上我只是使用相同的请求两个网页DefaultHttpClient

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;


public class ClientFormLogin {

    public static void main(String[] args) throws Exception {

        DefaultHttpClient httpclient = new DefaultHttpClient();

        //Handle first request.
        HttpGet httpget = new HttpGet("http://tweakers.net/nieuws/82969/amazon-nederland-opent-digitale-deuren-in-september.html");
        HttpResponse response = httpclient.execute(httpget);
        System.out.println("Execute finished");
        HttpEntity entity = response.getEntity();
        String page = readInput(entity.getContent());
        System.out.println("Request one finished without problems!");

        //Handle second request
        HttpGet httpost = new HttpGet("http://gathering.tweakers.net/forum/list_messages/1506977/last");
        response = httpclient.execute(httpost);
        entity = response.getEntity();
        page = readInput(entity.getContent());
        System.out.println("Request two finished without problems!");
    }

    private static String readInput(InputStream in) throws IOException {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        byte bytes[] = new byte[1024];

        int n = in.read(bytes);

        while (n != -1) {
            out.write(bytes,n);
            n = in.read(bytes);
        }

        return new String(out.toString());
    }
}

在运行我的示例时,出现以下错误

Request one finished without problems!
Exception in thread "main" org.apache.http.client.ClientProtocolException
    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:909)
    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:805)
    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:784)
    at ClientFormLogin.main(ClientFormLogin.java:29)
Caused by: org.apache.http.HttpException: Unable to establish route: planned = {}->http://gathering.tweakers.net; current = {}->http://tweakers.net
    at org.apache.http.impl.client.DefaultRequestDirector.establishRoute(DefaultRequestDirector.java:842)
    at org.apache.http.impl.client.DefaultRequestDirector.tryConnect(DefaultRequestDirector.java:645)
    at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:480)
    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:906)
    ... 3 more

任何人都可以给我一些指示,指出如何解决这个问题,但DefaultHttpClient对于每个请求都使用一个新的指示符。


编辑

我只是发现如果我留在同一个域中就没有问题,所以:

page1: 'http://tweakers.net/nieuws/82969/amazon-nederland-opent-digitale-deuren-in-september.html'
page2: 'http://tweakers.net/nieuws/82973/website-nujij-belandt-op-zwarte-lijst-google-door-malware.html'

如果我要:

page1: 'http://tweakers.net/nieuws/82969/amazon-nederland-opent-digitale-deuren-in-september.html'
page2: 'http://gathering.tweakers.net/forum/list_messages/1506076/last'

我得到了错误。

我在发布问题后一分钟就看到了Ofc。除非有人可以告诉我我如何可以同时使用2个独立域名,否则DefaultHttpClient我的问题已得到解答。

关于如何通过Apache的HttpClient在Couchdb中设置pipe理员给出一个curl的例子的问题我们已经讲解完毕,感谢您的阅读,如果还想了解更多关于Apache HttpClient 4.1-代理设置、apache HttpClient 学习系列--2 之HttpContext、Apache HttpClient在macOS上因Java 11失败、Apache HttpComponents:org.apache.http.client.ClientProtocolException等相关内容,可以在本站寻找。

本文标签: