使用HttpClient验证用户名和密码

I am trying to send a POST request to a php file which then sends back a json message for username and password authentication. with my code I get an error ArrayIndexOutOfBoundsException: length=0; index=0 on this line:

HttpGet get=new HttpGet(strings[0]);

In my code, when the login button is clicked, it calls an asyncTask class which then runs the application. it crashes before I can even test the code but I am not sure why. I am new to HttpClient so please be gentle. This is my snippet of code in the asynctask class

public class DownloadFilesTask extends AsyncTask<Void, Void, Void> {

private String name, pwd;
private LoginActivity loginActivity;
boolean bloggedIn;

public DownloadFilesTask(LoginActivity loginActivity,String name, String pwd){
    this.loginActivity=loginActivity;
    this.name=name;
    this.pwd=pwd;
}


@Override
protected Void doInBackground(Void... voids) {
    HttpClient httpClient=new DefaultHttpClient();
    HttpGet get=new HttpGet();
    try {
        URI website=new URI("login.php");
        get.setURI(website);
    } catch (URISyntaxException e) {
        e.printStackTrace();
    }

    HttpPost httpPost=new HttpPost("login.php");
    List<NameValuePair> nameValuePairs=new ArrayList<NameValuePair>(2);
    String result=null;
    nameValuePairs.add(new BasicNameValuePair("name", name));
    nameValuePairs.add(new BasicNameValuePair("password", pwd));
    try {
        httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
    HttpResponse response = null; //error
    try {
        response = httpClient.execute(httpPost);
    } catch (IOException e) {
        e.printStackTrace();
    }

    HttpEntity entity=response.getEntity();
    InputStream instream= null;
    try {
        instream = entity.getContent();
    } catch (IOException e) {
        e.printStackTrace();
    }
    result=convertStreamToString(instream);
    try {
        instream.close();
    } catch (IOException e) {
        e.printStackTrace();
    }



    if (Utility.isNotNull(name) && Utility.isNotNull(pwd)) {
        RequestParams params = new RequestParams();
        if (Utility.validate(name, pwd)) {
            params.put("username", name);
            params.put("password", pwd);
            bloggedIn=true;
            onPostExecute();
        } else {
            loginActivity.InvalidToast();
        }
    } else {
        loginActivity.EmptyToast();
    }
    return null;
}

private String convertStreamToString(InputStream instream) {
    BufferedReader reader=new BufferedReader(new InputStreamReader(instream));
    StringBuilder sb=new StringBuilder();
    String line=null;
    try {
        while ((line=reader.readLine())!=null){
            sb.append(line + "
");
        }
    } catch (IOException e) {
        e.printStackTrace();
    }finally{
        try {
            instream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return sb.toString();
}

protected void onPostExecute(){
    if (bloggedIn=true) {
        loginActivity.navigatetoMainActivity();
    }else{
        loginActivity.InvalidToast();
    }
}


private static class Utility {
    static Pattern pattern;
    static Matcher matcher;
    static Pattern pattern1;
    static Matcher matcher1;
    static String NAME_PATTERN="ABCDEF";
    static String PWD_PATTERN="ghijkl";

    public static boolean validate(String name,String pwd){
        pattern=Pattern.compile(NAME_PATTERN);
        pattern1=Pattern.compile(PWD_PATTERN);
        matcher=pattern.matcher(name);
        matcher1=pattern1.matcher(pwd);
        return matcher.matches()&& matcher1.matches();
    }

    public static boolean isNotNull(String name) {
        return name!=null && name.trim().length()>0 ? true: false;
    }
}

}

douxunzui1519
douxunzui1519 它仍然在同一行上给出一个错误:/同时使用HttpGet和HttpPost。难道我做错了什么?我已经按照你给我的每一个例子,它仍然会出错
4 年多之前 回复
douqi3913
douqi3913 这是如何使用HttpGet的一个很好的例子:stackoverflow.com/questions/20321799/android-http-get
4 年多之前 回复
doudan4834
doudan4834 更改doInBackground()方法的return语句以返回null;因为你不需要通过它发送数据。只需创建一个全局布尔值bLoggedIn并在登录成功时将其设置为true,然后在onPostExecute()方法中使用if语句检查登录是否成功并根据它进行调用。
4 年多之前 回复
doujiu1447
doujiu1447 将AsyncTask的实现更改为AsyncTask<Void,Void,Void>,因为您正在使用构造函数将数据发送到任务。然后将doInBackground()参数更改为Void...params。
4 年多之前 回复
dongmin4990
dongmin4990 你是什​​么意思?
4 年多之前 回复
duanjuduo4573
duanjuduo4573 使用空字符串数组调用doInBackground()方法。
4 年多之前 回复

1个回答

better to use on this way i given two way to get response from web services.

package com.example.testdemo;

import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.Settings.Global;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;

import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.RequestParams;

public class MainActivity extends Activity {
AsyncHttpClient client = new AsyncHttpClient();
RequestParams params = new RequestParams();
String resp;
public static String URL = "http://"here your server url other wise locatl     path set"/service/service/login";
String[] datafield, datavalue;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    // GetLogin();
    datafield = new String[] { "username", "password" };
    datavalue = new String[] { "hardik", "Parmar" }; // here set your edittext value
    new getServices().execute();

}

private class getServices extends AsyncTask<String, Void, Void> {
    private ProgressDialog Dialog = new ProgressDialog(MainActivity.this);

    protected void onPreExecute() {

        Dialog.setMessage("Please Wait...");
        Dialog.show();
    }

    @Override
    protected Void doInBackground(String... params) {
        // TODO Auto-generated method stub
        try {
            resp = postData(URL, datafield, datavalue);
            Log.e("SignUp", "Response : " + resp);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        // TODO Auto-generated method stub
        super.onPostExecute(result);
        Dialog.dismiss();
        try {
            JSONObject jsonObj = new JSONObject(resp);
            Log.e("get the JSON RESPONCES ", ": :: : : :: : : " + jsonObj);
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

private void GetLogin() {
    // TODO Auto-generated method stub
    params.put("username", "hardik");
    params.put("password", "Parmar");

    client.post(URL, params,
            new JsonHttpResponseHandler() {
                @Override
                public void onStart() {
                    // TODO Auto-generated method stub
                    super.onStart();
                    Log.e("Services ", "On start");
                }

                @Override
                public void onFailure(int statusCode, Header[] headers,
                        Throwable throwable, JSONArray errorResponse) {
                    // TODO Auto-generated method stub
                    super.onFailure(statusCode, headers, throwable,
                            errorResponse);
                    Log.e("Services ", "On failure  Array " + errorResponse);
                }

                @Override
                public void onSuccess(int statusCode, Header[] headers,
                        JSONObject response) {
                    // TODO Auto-generated method stub
                    super.onSuccess(statusCode, headers, response);
                    Log.e("Services ", "On Sucess " + response);
                }

                @Override
                public void onFinish() {
                    // TODO Auto-generated method stub
                    super.onFinish();
                    Log.e("Services ", "On finish");
                }

                @Override
                public void onFailure(int statusCode, Header[] headers,
                        Throwable throwable, JSONObject errorResponse) {
                    // TODO Auto-generated method stub
                    super.onFailure(statusCode, headers, throwable,
                            errorResponse);
                    Log.e("Services ", "On faulure Json Object "
                            + errorResponse);
                }
            });

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();
    if (id == R.id.action_settings) {
        return true;
    }
    return super.onOptionsItemSelected(item);
}

public static String postData(String mUrl, String[] datafield,
        String[] datavalue) {
    // TODO Auto-generated method stub
    String respStr = null;
    try {

        JSONObject json = new JSONObject();
        if (datafield != null) {
            for (int i = 0; i < datavalue.length; i++) {
                json.put(datafield[i], datavalue[i]);
            }
        }

        Log.e("json", "" + json);

        HttpClient httpClient = new DefaultHttpClient();
        HttpPost post = new HttpPost(mUrl);
        post.setHeader("content-type", "application/json; charset=UTF-8");

        StringEntity entity = new StringEntity(json.toString());
        post.setEntity(entity);

        HttpResponse resp = httpClient.execute(post);
        respStr = EntityUtils.toString(resp.getEntity());
    } catch (Throwable t) {
    }

    return respStr;

}
}

AsyncHttpClient this is a library for the getting response form server. GetLogin() method is using AsyncHttpClient. i always use this method.

and in your side may be mistake is

dongzhanlu8890
dongzhanlu8890 getLogin(); 正在使用AsyncHttpClient库,所以首先你将下载。
4 年多之前 回复
douye7033
douye7033 此外,我无法创建JsonHttpResponseHandler()的新实例
4 年多之前 回复
duanfu6160
duanfu6160 我看不到你在哪里使用getLogin();
4 年多之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
其他相关推荐
Python+OpenCV计算机视觉

Python+OpenCV计算机视觉

使用HttpClient进行登录验证

<div class="post-text" itemprop="text"> <p>I am trying to send a POST request to a php file and when the user is asked for login information, if wrong, it prints the json message from the php file and if right, it allows user to login. However, my application crashes, giving a NetworkOnThreadMainException pointing errors to three lines.</p> <pre><code> HttpResponse response=httpClient.execute(httpPost); public class LoginActivity extends ActionBarActivity { login(); </code></pre> <p>So how can i make this possible? This is some part of the code I have written:</p> <pre><code>public class LoginActivity extends ActionBarActivity { EditText et, et2; ImageButton ib5; String name,pwd; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); et = (EditText) findViewById(R.id.editText); et2 = (EditText) findViewById(R.id.editText2); ib5 = (ImageButton) findViewById(R.id.imageButton5); name=et.getText().toString(); pwd=et2.getText().toString(); final LoginActivity loginActivity=null; ib5.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { //login(); new DownloadFilesTask(loginActivity,name,pwd).doInBackground(); } }); } public void login() { new LoginTask(this, et.getText().toString(), et2.getText().toString()); } private class LoginTask { public LoginTask(LoginActivity loginActivity, String name, String pwd) { } } void navigatetoMainActivity() { Intent homeIntent = new Intent(getApplicationContext(), MainActivity.class); homeIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(homeIntent); } void InvalidToast(){ Toast.makeText(getApplicationContext(), "Please enter valid name and password", Toast.LENGTH_LONG).show(); } void EmptyToast(){ Toast.makeText(getApplicationContext(), "Please fill the form, don't leave any field blank", Toast.LENGTH_LONG).show(); } } </code></pre> <p>DownloadFilesTask.java</p> <pre><code>public class DownloadFilesTask extends AsyncTask&lt;String, String, String&gt; { private String name, pwd; private LoginActivity loginActivity; public DownloadFilesTask(LoginActivity loginActivity,String name, String pwd){ this.loginActivity=loginActivity; this.name=name; this.pwd=pwd; } @Override protected String doInBackground(String... strings) { HttpClient httpClient=new DefaultHttpClient(); HttpPost httpPost=new HttpPost("login.php"); List&lt;NameValuePair&gt; nameValuePairs=new ArrayList&lt;NameValuePair&gt;(2); String result=null; nameValuePairs.add(new BasicNameValuePair("name", name)); nameValuePairs.add(new BasicNameValuePair("password", pwd)); try { httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } HttpResponse response= null; try { response = httpClient.execute(httpPost); //error is given here } catch (IOException e) { e.printStackTrace(); } HttpEntity entity=response.getEntity(); InputStream instream= null; try { instream = entity.getContent(); } catch (IOException e) { e.printStackTrace(); } result=convertStreamToString(instream); try { instream.close(); } catch (IOException e) { e.printStackTrace(); } if (Utility.isNotNull(name) &amp;&amp; Utility.isNotNull(pwd)) { RequestParams params = new RequestParams(); if (Utility.validate(name, pwd)) { params.put("username", name); params.put("password", pwd); onPostExecute(); } else { loginActivity.InvalidToast(); } } else { loginActivity.EmptyToast(); } return result; } private String convertStreamToString(InputStream instream) { BufferedReader reader=new BufferedReader(new InputStreamReader(instream)); StringBuilder sb=new StringBuilder(); String line=null; try { while ((line=reader.readLine())!=null){ sb.append(line + " "); } } catch (IOException e) { e.printStackTrace(); }finally{ try { instream.close(); } catch (IOException e) { e.printStackTrace(); } } return sb.toString(); } protected void onPostExecute(){ loginActivity.navigatetoMainActivity(); } private static class Utility { static Pattern pattern; static Matcher matcher; static Pattern pattern1; static Matcher matcher1; static String NAME_PATTERN="SuperBoise"; static String PWD_PATTERN="qwerty"; public static boolean validate(String name,String pwd){ pattern=Pattern.compile(NAME_PATTERN); pattern1=Pattern.compile(PWD_PATTERN); matcher=pattern.matcher(name); matcher1=pattern1.matcher(pwd); return matcher.matches()&amp;&amp; matcher1.matches(); } public static boolean isNotNull(String name) { return name!=null &amp;&amp; name.trim().length()&gt;0 ? true: false; } } } </code></pre> </div>

在golang的http请求中附加用户名和密码

<div class="post-text" itemprop="text"> <p>what i have tried till now is like and http request formed now is:<code>curl -X POST http://localhost:8080/v1.0</code></p> <pre><code>l_httpClient_ptr := http.Client{ Timeout: timeout, } var l_resp_ptr *http.Response var l_resp_byte []byte l_resp_ptr, r_err = l_httpClient_ptr.Post(p_url_str, "text/xml; charset=utf-8", bytes.NewBufferString(p_request_str)) l_resp_byte, r_err = ioutil.ReadAll(l_resp_ptr.Body) l_resp_ptr.Body.Close() r_response_str = string(l_resp_byte) return } </code></pre> <p>Here I am able to send only request xml along with URL. And with my code I don't know how to send Username and password along with url that is it should be like following URL:</p> <pre><code>curl -H "ChannelName: guest" -H "ChannelPassword: guest" -X POST http://localhost:8080/v1.0/ </code></pre> </div>

如何在Symfony HttpClient组件的CurlHttpClient中添加具有IP /端口和用户名/密码的代理?

<div class="post-text" itemprop="text"> <p>I'm using Symfony HttpClient Component, it became necessary to use it with a proxy. Open proxy with the port, I can easily configure with the default configuration when instantiating CurlHttpClient class, but I can't set username and password for private proxy</p> <p>Example of default configuration:</p> <pre class="lang-php prettyprint-override"><code>use Symfony\Component\HttpClient\CurlHttpClient; $httpClient = new CurlHttpClient([ 'http_version' =&gt; '2.0', 'proxy' =&gt; 'x.xx.xxx.xxx:8000', ]); </code></pre> <p>I try to add additional configuration on the extra options, and try other combinations, but can't find the right way.</p> <p>with plain PHP and cURL everything works fine.</p> <p>Please, help me, configure the Symfony HttpClient Component with a private proxy.</p> </div>

.NETCORE如何调用带用户名密码验证和WS验证的WebService?

各位大神,我用.NET引用该webservice,会自动在web.config里创建节点。并自己修改header值。 ![图片说明](https://img-ask.csdn.net/upload/201903/27/1553688980_854974.png) 但是到.NETCORE里就不知道怎么办了,不知道在哪边配置header. ``` //不知道为什么引用过来的WebService没有空的构造函数,必须要有个EndpointConfiguration NotificationServiceSoapClient client13 = new NotificationServiceSoapClient(NotificationServiceSoapClient.EndpointConfiguration.NotificationServiceSoap); var tt = client13.NotifyAsync(JsonConvert.SerializeObject(notice));//执行到这一步就报下面这个错误 ``` ![图片说明](https://img-ask.csdn.net/upload/201903/27/1553688759_469347.png) 我现在该怎么办?如何设置Header和wsse:Security?

httpclient 实现模拟登陆的问题

我想用httpclient 做一个摸模拟登陆人人网(就是类似的网站,要输入用户名密码的那种,论坛啦网友啦)的应用程序,我知道用httpclient的post方法实现向服务器提交参数(账户名和密码)的方法,可是接下来我要怎样才能知道我是否登陆成功了呢?如果登录成功就放会“登陆成功!”反之则返回“登录失败!”我要如何通过服务器返回来的信息获得是否登录成功的信息呢?希望给位大侠能不吝赐教啊!

Android使用HttpClient发送请求

发送数据包到服务器,网络正常,服务器也是正常的,在一段时间内服务器返回的信息正确,一段时间没返回的信息错误,大神们知道这种情况是怎么回事???

用HttpClient模拟登录带验证码的网站,如何保证获取的验证码和提交的验证码一致

使用程序模拟登录一个带验证码的网站,我先获取验证码图片的路径, 然后把验证码图片保存到本地,手动识别后,将验证码和用户名和密码一起 post提交模拟登录,我怀疑是获取的验证码和提交的验证码不一致的导致的, 在下载的时候也去请求了这个验证码图片的路径,这样验证码也会刷新,这样导致 验证码不一致的问题出现,请问大神们有什么好的方法来处理这个问题吗? ps:我尝试百度了下,有人说将下载验证码图片时获取的Cookie取下来然后在和 验证码一起post请求的时候再在之前的Cookie带过去,这样可以解决这个问题, 但是我试了,还是不行。

servlet中不能使用HttpClient吗?

servlet中不能使用HttpClient吗? 在servlet中使用HttpClient,包已配置好,编译通过。 package use; import java.io.*; import javax.servlet.*; import javax.servlet.http.*; import bean.Stock; import org.apache.commons.httpclient.methods.GetMethod; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager; import java.util.TimerTask; import java.util.HashMap; import java.util.Timer; public class UseServlet extends HttpServlet { private HashMap<String, Stock> stocks; [b] private HttpClient httpclient = new HttpClient(new MultiThreadedHttpConnectionManager());[/b] public void init(ServletConfig config) throws ServletException { super.init(config); } ............ ......... 但在网页中调用时,出现错误: [b]javax.servlet.ServletException: Error instantiating servlet class use.UseServlet[/b] org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102) org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:263) org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:844) org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:584) org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:447) java.lang.Thread.run(Unknown Source) 问题在哪?请帮忙看一下!

关于HttpClient的问题,如何使用HttpClient重定向?

``` /* * HttpRequestProxy.java * * Created on November 3, 2008, 9:53 AM */ import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Set; import org.apache.commons.httpclient.Header; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.HttpException; import org.apache.commons.httpclient.HttpMethod; import org.apache.commons.httpclient.NameValuePair; import org.apache.commons.httpclient.SimpleHttpConnectionManager; import org.apache.commons.httpclient.methods.GetMethod; import org.apache.commons.httpclient.methods.PostMethod; public class HttpRequestProxy { // 超时间隔 private static int connectTimeOut = 60000; // 让connectionmanager管理httpclientconnection时是否关闭连接 private static boolean alwaysClose = false; // 返回数据编码格式 private String encoding = "UTF-8"; private final HttpClient client = new HttpClient(); public HttpClient getHttpClient() { return client; } /** * 用法: HttpRequestProxy hrp = new HttpRequestProxy(); * hrp.doRequest("http://www.163.com",null,null,"gbk"); * * @param url * 请求的资源URL * @param postData * POST请求时form表单封装的数据 没有时传null * @param header * request请求时附带的头信息(header) 没有时传null * @param encoding * response返回的信息编码格式 没有时传null * @return response返回的文本数据 * @throws CustomException */ public String doRequest(String url, Map postData, Map header, String encoding) throws Exception { String responseString = null; // 头部请求信息 Header[] headers = null; if (header != null) { Set entrySet = header.entrySet(); int dataLength = entrySet.size(); headers = new Header[dataLength]; int i = 0; for (Iterator itor = entrySet.iterator(); itor.hasNext();) { Map.Entry entry = (Map.Entry) itor.next(); headers[i++] = new Header(entry.getKey().toString(), entry.getValue().toString()); } } // post方式 if (postData != null) { PostMethod postRequest = new PostMethod(url.trim()); if (headers != null) { for (int i = 0; i < headers.length; i++) { postRequest.setRequestHeader(headers[i]); } } Set entrySet = postData.entrySet(); int dataLength = entrySet.size(); NameValuePair[] params = new NameValuePair[dataLength]; int i = 0; for (Iterator itor = entrySet.iterator(); itor.hasNext();) { Map.Entry entry = (Map.Entry) itor.next(); params[i++] = new NameValuePair(entry.getKey().toString(), entry.getValue().toString()); } postRequest.setRequestBody(params); try { responseString = this.executeMethod(postRequest, encoding); } catch (Exception e) { throw e; } finally { postRequest.releaseConnection(); } } return responseString; } private String executeMethod(HttpMethod request, String encoding) throws Exception { String responseContent = null; InputStream responseStream = null; BufferedReader rd = null; try { this.getHttpClient().executeMethod(request); if (encoding != null) { responseStream = request.getResponseBodyAsStream(); rd = new BufferedReader(new InputStreamReader(responseStream, encoding)); String tempLine = rd.readLine(); StringBuffer tempStr = new StringBuffer(); String crlf = System.getProperty("line.separator"); while (tempLine != null) { tempStr.append(tempLine); tempStr.append(crlf); tempLine = rd.readLine(); } responseContent = tempStr.toString(); } else responseContent = request.getResponseBodyAsString(); Header locationHeader = request.getResponseHeader("location"); // 返回代码为302,301时,表示页面己经重定向,则重新请求location的url,这在 // 一些登录授权取cookie时很重要 if (locationHeader != null) { String redirectUrl = locationHeader.getValue(); this.doRequest(redirectUrl, null, null, null); } } catch (HttpException e) { throw new Exception(e.getMessage()); } catch (IOException e) { throw new Exception(e.getMessage()); } finally { if (rd != null) try { rd.close(); } catch (IOException e) { throw new Exception(e.getMessage()); } if (responseStream != null) try { responseStream.close(); } catch (IOException e) { throw new Exception(e.getMessage()); } } return responseContent; } /** * 特殊请求数据,这样的请求往往会出现redirect本身而出现递归死循环重定向 所以单独写成一个请求方法 * 比如现在请求的url为:http://localhost:8080/demo/index.jsp 返回代码为302 * 头部信息中location值为:http://localhost:8083/demo/index.jsp * 这时httpclient认为进入递归死循环重定向,抛出CircularRedirectException异常 * * @param url * @return * @throws CustomException */ public String doSpecialRequest(String url, int count, String encoding) throws Exception { String str = null; InputStream responseStream = null; BufferedReader rd = null; GetMethod getRequest = new GetMethod(url); // 关闭httpclient自动重定向动能 getRequest.setFollowRedirects(false); try { this.client.executeMethod(getRequest); Header header = getRequest.getResponseHeader("location"); if (header != null) { // 请求重定向后的URL,count同时加1 this.doSpecialRequest(header.getValue(), count + 1, encoding); } // 这里用count作为标志位,当count为0时才返回请求的URL文本, // 这样就可以忽略所有的递归重定向时返回文本流操作,提高性能 if (count == 0) { getRequest = new GetMethod(url); getRequest.setFollowRedirects(false); this.client.executeMethod(getRequest); responseStream = getRequest.getResponseBodyAsStream(); rd = new BufferedReader(new InputStreamReader(responseStream, encoding)); String tempLine = rd.readLine(); StringBuffer tempStr = new StringBuffer(); String crlf = System.getProperty("line.separator"); while (tempLine != null) { tempStr.append(tempLine); tempStr.append(crlf); tempLine = rd.readLine(); } str = tempStr.toString(); } } catch (HttpException e) { throw new Exception(e.getMessage()); } catch (IOException e) { throw new Exception(e.getMessage()); } finally { getRequest.releaseConnection(); if (rd != null) try { rd.close(); } catch (IOException e) { throw new Exception(e.getMessage()); } if (responseStream != null) try { responseStream.close(); } catch (IOException e) { throw new Exception(e.getMessage()); } } return str; } public static void main(String[] args) throws Exception { HttpRequestProxy hrp = new HttpRequestProxy(); Map date = new HashMap(); date.put("jyidApplet", "1"); date.put("codeNumApplet", "1"); date.put("jymxIdApplet", "447"); date.put("patientIdApplet", "1118"); String str = hrp.doRequest("http://127.0.0.1:8080/lis/mz/addTM",date, null, null); System.out.println(str); } } ```

Yii2:登录时设置错误的用户名或密码信息

<div class="post-text" itemprop="text"> <p>I am using yii2 basic for my application. When I login to my application by typing wrong username or password, it does not set any message like incorrect username or password. The browser simply refreshes the page.</p> <p>This is my <strong>site/login.php</strong> file:</p> <pre><code>&lt;?php use yii\helpers\Html; use yii\bootstrap\ActiveForm; /* @var $this yii\web\View */ /* @var $form yii\bootstrap\ActiveForm */ /* @var $model app\models\LoginForm */ $this-&gt;title = 'Login'; $this-&gt;params['breadcrumbs'][] = $this-&gt;title; ?&gt; &lt;div class="site-login"&gt; &lt;h1&gt;&lt;?= Html::encode($this-&gt;title) ?&gt;&lt;/h1&gt; &lt;p&gt;Please fill out the following fields to login:&lt;/p&gt; &lt;?php $form = ActiveForm::begin([ 'id' =&gt; 'login-form', 'options' =&gt; ['class' =&gt; 'form-horizontal'], 'fieldConfig' =&gt; [ 'template' =&gt; "{label} &lt;div class=\"col-lg-3\"&gt;{input}&lt;/div&gt; &lt;div class=\"col-lg-8\"&gt;{error}&lt;/div&gt;", 'labelOptions' =&gt; ['class' =&gt; 'col-lg-1 control-label'], ], ]); ?&gt; &lt;?= $form-&gt;field($model, 'username') ?&gt; &lt;?= $form-&gt;field($model, 'password')-&gt;passwordInput() ?&gt; &lt;?= $form-&gt;field($model, 'rememberMe')-&gt;checkbox([ 'template' =&gt; "&lt;div class=\"col-lg-offset-1 col-lg-3\"&gt;{input} {label}&lt;/div&gt; &lt;div class=\"col-lg-8\"&gt;{error}&lt;/div&gt;", ]) ?&gt; &lt;div class="form-group"&gt; &lt;div class="col-lg-offset-1 col-lg-11"&gt; &lt;?= Html::submitButton('Login', ['class' =&gt; 'btn btn-primary', 'name' =&gt; 'login-button']) ?&gt; &lt;/div&gt; &lt;/div&gt; &lt;?php ActiveForm::end(); ?&gt; &lt;!-- &lt;div class="col-lg-offset-1" style="color:#999;"&gt; You may login with &lt;strong&gt;admin/admin&lt;/strong&gt; or &lt;strong&gt;demo/demo&lt;/strong&gt;.&lt;br&gt; To modify the username/password, please check out the code &lt;code&gt;app\models\User::$users&lt;/code&gt;. &lt;/div&gt; --&gt; &lt;/div&gt; </code></pre> <p>And here is my action for login:</p> <pre><code>public function actionLogin() { if (!\Yii::$app-&gt;user-&gt;isGuest) { return $this-&gt;goHome(); } $model = new LoginForm(); if ($model-&gt;load(Yii::$app-&gt;request-&gt;post())) { $model-&gt;password = md5($model-&gt;password); $model-&gt;login(); return $this-&gt;redirect(['site/index']); } return $this-&gt;render('login', [ 'model' =&gt; $model, ]); } </code></pre> <p>Any help would be greatly appreciated.</p> </div>

Httpclient带登录的爬虫短信验证码

现在做个爬虫,但是数据都是登陆后才能获取,出现个问题,一直用代理,但是代理现在已经登录不了了。会直接返回个错误信息。 更换了代理商,但是会出现短信验证码的问题。我用httpclient模拟登录,怎么能验证短信呢? 不知道大家有没有更好的策略方案。求打赏!!!!!!!!!!!!!!!!不胜感激

httpclient包使用的问题

这是我的代码: import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.Scanner; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.NameValuePair; import org.apache.commons.httpclient.methods.GetMethod; import org.apache.commons.httpclient.methods.PostMethod; public class CatchWeb { static HttpClient client = new HttpClient(); public static void main(String[] args) { Init(); } private static void Init() { getImage("【我的账号】","【我的密码】"); } private static void getImage(String name_get, String password_get) { /**获取验证码图片*/ GetMethod get = new GetMethod("http://jwxt.gcu.edu.cn/CheckCode.aspx"); try { client.executeMethod(get); File storeFile = new File("D:/verifycode.jpg"); InputStream is = get.getResponseBodyAsStream(); FileOutputStream fos = new FileOutputStream(storeFile); byte[] b = new byte[1024]; while ((is.read(b)) != -1) { fos.write(b); } is.close(); fos.close(); String codeVal = getCode(); System.out.println(codeVal); postRequest(name_get, password_get, codeVal); } catch (IOException e) { e.printStackTrace(); } } private static void postRequest(String name_data, String password_data,String code) { PostMethod postMethod = new PostMethod("http://jwxt.gcu.edu.cn/default2.aspx"); NameValuePair[] data = { new NameValuePair("__VIEWSTATE", "dDwyODE2NTM0OTg7Oz7c6+5UiE0x3F6KGVy0J/g7vA1NIQ=="), new NameValuePair("txtUserName", name_data), new NameValuePair("TextBox2", password_data), new NameValuePair("txtSecretCode", code), new NameValuePair("RadioButtonList1", "学生"), new NameValuePair("Button1", "") }; postMethod.setRequestBody(data); try { client.executeMethod(postMethod); String text = postMethod.getResponseBodyAsString(); System.out.println(text); if (text.contains("验证码不正确")) { System.out.println("验证码不正确"); } else if(text.contains("密码错误")){ System.out.println("密码错误"); } else{ System.out.println("登录成功"); } } catch (IOException e) { e.printStackTrace(); } } private static String getCode() { String valCode = "dny4"; String path = "d://verifycode.jpg"; Scanner sca=new Scanner(System.in); valCode=sca.next(); return valCode; } } 输出结果: 当输入错误密码时会提示密码错误,请问为什么输入正确时就提示如图信息 信息: Redirect requested but followRedirects is disabled

怎么使用httpclient实现http接口调用实例

接口地址: https://data2.contec365.com/login.php 请求方式: post 需要传递参数:![图片说明](https://img-ask.csdn.net/upload/201606/29/1467194093_742151.png) 参数内容为xml格式![图片说明](https://img-ask.csdn.net/upload/201606/29/1467194080_167521.png) 输出![图片说明](https://img-ask.csdn.net/upload/201606/29/1467194221_53039.png) 格式为xml格式:![图片说明](https://img-ask.csdn.net/upload/201606/29/1467194307_683270.png) code: 为提示信息 文档就是这样的,我应该怎么写,能不能写个示例,还有 servlet怎么调用,给点建议,不胜感激,谢谢,困扰我好多天了,希望能给出代码,因为我没写,也上网查了都找不到合适的,所以希望给出代码,谢谢

使用HttpClient访问网络

使用HttpClient访问网络 清单文件 <uses-sdk android:minSdkVersion="14" android:targetSdkVersion="19" /> 出错 用 <uses-sdk android:minSdkVersion="9" /> 就没错。请问是什么问题

httpclient 动态网页获取

public static String getHtmlByUrl(String url){ String html = null; HttpClient httpClient = new DefaultHttpClient();//创建httpClient对象 HttpGet httpget = new HttpGet(url);//以get方式请求该URL try { HttpResponse responce = httpClient.execute(httpget);//得到responce对象 int resStatu = responce.getStatusLine().getStatusCode();//返回码 if (resStatu==HttpStatus.SC_OK) {//200正常 其他就不对 //获得相应实体 HttpEntity entity = responce.getEntity(); System.out.println(Integer.toString(resStatu)); if (entity!=null) { html = EntityUtils.toString(entity);//获得html源代码 } } } catch (Exception e) { System.out.println("访问【"+url+"】出现异常!"); e.printStackTrace(); } finally { httpClient.getConnectionManager().shutdown(); } //System.out.println(html); return html; } 上述代码只能抓静态网页数据 麻烦看下上面代码怎么改才能获取动态网页数据啊

java使用httpclient向百度的收录入口提交URL报 403错误

package com.galaxy.promotion.baidu; import java.io.IOException; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.HttpException; import org.apache.commons.httpclient.NameValuePair; import org.apache.commons.httpclient.methods.PostMethod; public class Test { public static void main(String[] args) throws HttpException, IOException { HttpClient httpclient = new HttpClient(); // 创建post方法实例 PostMethod postMethod = new PostMethod("http://zhanzhang.baidu.com/linksubmit/urlsubmit"); // 填入各个表单域的值 NameValuePair[] data = { new NameValuePair("url", "www.example.com") }; // 将表单的值放入到post方法中 postMethod.setRequestBody(data); // 执行post方法 int statusCode = httpclient.executeMethod(postMethod); System.out.println(statusCode); System.out.println(postMethod.getStatusLine()); } }

java实现httpclient上传文件和普通参数到servlet

哪位能推荐一个好的方法,实现httpclient上传文件和普通参数到servlet,post方法,servlet端是普通web项目,不能用spring相关方法。自测使用的MultipartEntityBuilder,但是servlet接收不到上传的参数,在线急等

访问外网接口 在服务器上curl没有问题 但是使用httpclient就超时

访问外网接口 在服务器上curl没有问题 但是使用httpclient就超时 能是什么原因啊 求大神帮忙解决

httpclient对象池设置代理问题,求大神

PoolingHttpClientConnectionManager上能设置带认证的代理IP时不是也要一个host,那个对象不给行吗,只给用户名密码,ip设置到request上可以吗 我想使用 httpclient的对象池并发访问但是想每一个访问的request都是不同的ip但是设置对象池的时候要用户名密码但是设置用户名密码的时候需要给代理的,大家有没有解决的办法

2019 Python开发者日-培训

2019 Python开发者日-培训

150讲轻松搞定Python网络爬虫

150讲轻松搞定Python网络爬虫

设计模式(JAVA语言实现)--20种设计模式附带源码

设计模式(JAVA语言实现)--20种设计模式附带源码

YOLOv3目标检测实战:训练自己的数据集

YOLOv3目标检测实战:训练自己的数据集

java后台+微信小程序 实现完整的点餐系统

java后台+微信小程序 实现完整的点餐系统

三个项目玩转深度学习(附1G源码)

三个项目玩转深度学习(附1G源码)

初级玩转Linux+Ubuntu(嵌入式开发基础课程)

初级玩转Linux+Ubuntu(嵌入式开发基础课程)

2019 AI开发者大会

2019 AI开发者大会

玩转Linux:常用命令实例指南

玩转Linux:常用命令实例指南

一学即懂的计算机视觉(第一季)

一学即懂的计算机视觉(第一季)

4小时玩转微信小程序——基础入门与微信支付实战

4小时玩转微信小程序——基础入门与微信支付实战

Git 实用技巧

Git 实用技巧

Python数据清洗实战入门

Python数据清洗实战入门

使用TensorFlow+keras快速构建图像分类模型

使用TensorFlow+keras快速构建图像分类模型

实用主义学Python(小白也容易上手的Python实用案例)

实用主义学Python(小白也容易上手的Python实用案例)

程序员的算法通关课:知己知彼(第一季)

程序员的算法通关课:知己知彼(第一季)

MySQL数据库从入门到实战应用

MySQL数据库从入门到实战应用

机器学习初学者必会的案例精讲

机器学习初学者必会的案例精讲

手把手实现Java图书管理系统(附源码)

手把手实现Java图书管理系统(附源码)

极简JAVA学习营第四期(报名以后加助教微信:eduxy-1)

极简JAVA学习营第四期(报名以后加助教微信:eduxy-1)

.net core快速开发框架

.net core快速开发框架

玩转Python-Python3基础入门

玩转Python-Python3基础入门

Python数据挖掘简易入门

Python数据挖掘简易入门

微信公众平台开发入门

微信公众平台开发入门

程序员的兼职技能课

程序员的兼职技能课

Windows版YOLOv4目标检测实战:训练自己的数据集

Windows版YOLOv4目标检测实战:训练自己的数据集

HoloLens2开发入门教程

HoloLens2开发入门教程

微信小程序开发实战

微信小程序开发实战

Java8零基础入门视频教程

Java8零基础入门视频教程

相关热词 c#树形选择 c#中类图的使用方法 c# 传参 调用exe c# 怎么定义方法 c# 修改本地时间 c#前台怎么读取资源文件 c# xml转list c#实现框选截图 m*m乘法表c# c# 乘法99表
立即提问