标签: httpclient

HttpClient响应处理程序始终返回闭合流

我是Java开发的新手,所以请耐心等待.另外,我希望我不是tl的博士;博士 :).

我正在使用HttpClient通过Http(duh!)发出请求,并且我已经让它为一个接收URL作为查询字符串参数的简单servlet工作.我意识到我的代码可以使用一些重构,所以我决定自己做HttpResponseHandler,清理代码,使其可重用并改进异常处理.

我目前有这样的事情:

public class HttpResponseHandler implements ResponseHandler<InputStream>{

    public InputStream handleResponse(HttpResponse response)
            throws ClientProtocolException, IOException {

        int statusCode = response.getStatusLine().getStatusCode();
        InputStream in = null;

        if (statusCode != HttpStatus.SC_OK) {
            throw new HttpResponseException(statusCode, null);
        } else {
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                in = entity.getContent();
                // This works
                // for (int i;(i = in.read()) >= 0;) System.out.print((char)i); 
            }
        }
        return in;
    }
}
Run Code Online (Sandbox Code Playgroud)

在我提出实际请求的方法中:

HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget …
Run Code Online (Sandbox Code Playgroud)

java inputstream httpclient handler

1
推荐指数
1
解决办法
1万
查看次数

在Android服务中安排的AsynTask只执行一次

我正在尝试创建简单的Android程序,每30*1000毫秒拉一次Web服务器.我在我的应用程序中有专门的服务 - PollerService

Android Manifest.xml:
<application android:icon="@drawable/icon" android:label="@string/app_name">
    <activity android:name=".PullServerAndListenActivivty"
        android:label="@string/app_name">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <service android:name=".PollerService" />
</application>
Run Code Online (Sandbox Code Playgroud)

该类创建计划执行程序并注册其计时器任务以开始调用Engine,以便拉出服务器.

PollerService.java:

public class PollerService extends Service {
public static final int INTERVAL = 20*1000;
private ScheduledExecutorService executor;

public void onCreate() {
    super.onCreate();
    executor = Executors.newSingleThreadScheduledExecutor();
    executor.scheduleAtFixedRate(new TimerTask() {
        public void run() {
            Engine.tick ();             
        }
    }, 0, INTERVAL, TimeUnit.MILLISECONDS);
}

public void onDestroy() {
    executor.shutdownNow();
}

public IBinder onBind(Intent arg0) {
    return null;
};
} …
Run Code Online (Sandbox Code Playgroud)

java multithreading android httpclient android-asynctask

1
推荐指数
1
解决办法
2342
查看次数

处理HttpClient(Httpget)超时

所以我正在运行一个多线程程序,它会对api和一些想要抓取的网页进行大量调用.在一些不寻常的情况下,httpget将失败并导致程序"冻结"(线程永不退出,线程池永不关闭,主要永不退出等)

我需要为我正在建立的http连接设置超时.我正在使用DefaultHttpClient

DefaultHttpClient httpclient = new DefaultHttpClient();
Run Code Online (Sandbox Code Playgroud)

而且我没有设置任何参数.

有人可以帮我解决这些问题,或者至少指出我应该寻找处理超时的地方吗?(Apache似乎有很好的库,似乎从来没有好的例子)

java httpclient apache-httpclient-4.x

1
推荐指数
1
解决办法
3278
查看次数

HttpGet添加标题

我正在创建一个httpClient,我想在我的HttpGet请求中添加某些标头
我当前的代码产生以下请求.

GET /folder/index.html HTTP/1.0
主机:localhost:4444
连接:Keep-Alive
User-Agent:Apache-HttpClient/4.2.1(java 1.5)

我想要的是在该请求中添加另一个标头(If-Modified-Since).
我该怎么做?
谢谢 :)

public String httpGet(String s) {
    String url = s;
    StringBuilder body = new StringBuilder();
    httpclient = new DefaultHttpClient(); // create new httpClient
    HttpGet httpGet = new HttpGet(url); // create new httpGet object



    try {
        response = httpclient.execute(httpGet); // execute httpGet
        StatusLine statusLine = response.getStatusLine();
        int statusCode = statusLine.getStatusCode();
        if (statusCode == HttpStatus.SC_OK) {
            // System.out.println(statusLine);
            body.append(statusLine + "\n");
            HttpEntity e = response.getEntity();
            String entity = EntityUtils.toString(e);
            body.append(entity); …
Run Code Online (Sandbox Code Playgroud)

java http httpclient http-headers

1
推荐指数
1
解决办法
2万
查看次数

将android连接到openLDAP服务器

我被分配了一项任务,从 android 连接到 LDAP 服务器。从 android 执行身份验证过程。我正在使用 openLDAP。我对此完全陌生。任何人都可以帮我解决一些代码或演示代码,显示 android 与 LDAP 服务器连接并进行身份验证。这

  Port no-389
  SSL Port-636
  IP Address-LGSPC3
  username-->cn=name,cn=users,dc=mydeomain,dc=com

  serverlist-ldap://server1
Run Code Online (Sandbox Code Playgroud)

先感谢您

java android httpclient openldap unboundid-ldap-sdk

1
推荐指数
1
解决办法
3022
查看次数

如何设置httpclient的字符编码

我正在使用这个httpclient:http://loopj.com/android-async-http/我正在使用这个httpclient 获取json.我想设置这个httpclient的字符enconding.客户端返回的JSONObject包含土耳其字符,例如şğöü.但它已损坏,我无法查看这些字符.

如何设置此httpclient的字符编码?

android httpclient character-encoding

1
推荐指数
1
解决办法
4604
查看次数

通过 HttpClient 登录

我正在使用此代码来使用 ASP.NET MVC 5 WebAPI2。

static async Task RunAsync()
        {
            using (var client = new HttpClient())
            {
               client.BaseAddress = new Uri("http://localhost:52967/");
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                // New code:
                HttpResponseMessage response = await client.GetAsync("api/Account/Login");
                if (response.IsSuccessStatusCode)
                {
                    var data = await response.Content.ReadAsStringAsync();

                }
            }
        }
Run Code Online (Sandbox Code Playgroud)

AccountController我创建以下方法下

[HttpPost]
        [AllowAnonymous]
        [Route("Login")]
        public HttpResponseMessage Login(string username, string password)
        {
            try
            {
                var identityUser = UserManager.Find(username, password);

                if (identityUser != null)
                {
                    var identity = new ClaimsIdentity(Startup.OAuthOptions.AuthenticationType);
                    identity.AddClaim(new Claim(ClaimTypes.Name, username));

                    AuthenticationTicket ticket = new …
Run Code Online (Sandbox Code Playgroud)

c# httpclient asp.net-web-api

1
推荐指数
1
解决办法
9960
查看次数

无法在 Android Studio 中解析 DefaultHttpClient

我正在关注本教程:https : //www.youtube.com/watch?v=I58TkCi73ew

在视频的大约中间,Derek Banas 插入 DefaultHttpClient 显然允许从应用程序访问浏览器/网络。但是当我把确切的代码放到IDE中时,却报错说Android studio无法解析DefaultHttpClient。这是带有 DefaultHttpClient 的代码:

class SaveTheFeed extends AsyncTask<Void, Void, Void>{

    String jsonString = "";

    String result = "";

    @Override
    protected Void doInBackground(Void... voids) {

        EditText translateEditText = (EditText) findViewById(R.id.editText);

        String wordsToTranslate = translateEditText.getText().toString();

        wordsToTranslate = wordsToTranslate.replace(" ", "+");

        DefaultHttpClient httpClient = new DefaultHttpClient(new BasicHttpParams());

        return null;
    }
}
Run Code Online (Sandbox Code Playgroud)

我尝试导入这些包,但包中也有错误。

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
Run Code Online (Sandbox Code Playgroud)

我试图在其他问题中查看其他解决方案,但没有一个真正吸引我的问题。谁能帮我这个?

谢谢!?

注意:这个问题不是Can't import …

java android httpclient android-studio

1
推荐指数
1
解决办法
5447
查看次数

VS 2010 中没有等待的 HttpClient.PostAsync

这是这个问题的后续:

如何使用 HTTP POST multipart/form-data 将文件上传到服务器

上传多部分表单数据似乎是一个很好的解决方案。该库可通过 NuGet 在 VS 2010 中使用。

但是,下面的代码使用了await关键字,这在 VS 2010 中不可用。

如果不使用,该代码的正确等价物是await什么?

HttpClient httpClient = new HttpClient();
MultipartFormDataContent form = new MultipartFormDataContent();

form.Add(new StringContent(username), "username");
form.Add(new StringContent(useremail), "email");
form.Add(new StringContent(password), "password");
form.Add(new StringContent(usertype), "user_type");
form.Add(new StringContent(subjects), "subjects");
form.Add(new ByteArrayContent(imagebytearraystring, 0, imagebytearraystring.Count()), "profile_pic", "hello1.jpg");
HttpResponseMessage response = await httpClient.PostAsync("PostUrl", form);

response.EnsureSuccessStatusCode();
httpClient.Dispose();
string sd = response.Content.ReadAsStringAsync().Result;
Run Code Online (Sandbox Code Playgroud)

c# asynchronous httpclient async-await

1
推荐指数
1
解决办法
4599
查看次数

连接失败:使用 Java、Apache HTTP 客户端测试 API 超时

我正在尝试使用 Java 测试 API。我正在使用 Java 8、Apache HTTP 客户端 4.5.3 来测试它。我尝试了许多不同的方法来使用 Java .net 类、Apache HTTP 客户端进行测试,但每次都出现相同的问题;

线程“main” org.apache.http.conn.HttpHostConnectException 中的异常:连接到 api.github.com:443 [api.github.com/192.30.253.116, api.github.com/192.30.253.117] 失败:连接超时输出:连接在 org.apache.http.impl.conn.DefaultHttpClientConnectionOperator.connect(DefaultHttpClientConnectionOperator.java:159)

每次我都抽出时间。但是如果我在浏览器中使用相同的 URL,我就会得到结果。

有人可以帮我指出问题吗?是设置问题还是代码问题?

尝试了互联网上几乎所有可用的代码。我是 API 测试的初学者,并没有深入了解 HTTP 工作流程。

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.HttpClientBuilder;

import java.io.IOException;
import java.net.*;

public class API {


    public static void main(String args[]) throws IOException, URISyntaxException {


        HttpUriRequest request = new HttpGet( "https://api.github.com" );

        // When
        HttpResponse response = HttpClientBuilder.create().build().execute( request );

        System.out.println(response.getStatusLine().getStatusCode());
    }
}
Run Code Online (Sandbox Code Playgroud)

使用 Java .net 包

import java.io.IOException; …
Run Code Online (Sandbox Code Playgroud)

java apache api httpclient

1
推荐指数
1
解决办法
1万
查看次数