JAVA http 要求用户名密码验证

marven

<!-- https://mvnrepository.com/artifact/commons-httpclient/commons-httpclient -->
<dependency>
<groupId>commons-httpclient</groupId>
<artifactId>commons-httpclient</artifactId>
<version>3.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-logging/commons-logging -->
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/avalon-framework/avalon-framework -->
<dependency>
<groupId>avalon-framework</groupId>
<artifactId>avalon-framework</artifactId>
<version>4.1.5</version>
</dependency>
<!-- https://mvnrepository.com/artifact/logkit/logkit -->
<dependency>
<groupId>logkit</groupId>
<artifactId>logkit</artifactId>
<version>2.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-codec/commons-codec -->
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.11</version>
</dependency>
<!-- 表示开发的时候引入,发布的时候不会加载此包 -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>


    /**
     * 
     * @param url  
     * @param user
     * @param password
     * @param jsonParams
     * @return
     */

public static String postByCredential(String url, String user, String password, String jsonParams) {
String ret = "";
HttpClient httpClient = null;
PostMethod method = null;
UsernamePasswordCredentials creds = null;
StringRequestEntity requestEntity = null;
try {
httpClient =new HttpClient(new HttpClientParams(),new SimpleHttpConnectionManager(true));  
creds = new UsernamePasswordCredentials(user, password);
httpClient.getState().setCredentials(AuthScope.ANY, creds);
method = new PostMethod(url);
method.setDoAuthentication(true);
requestEntity = new StringRequestEntity(jsonParams,"application/json","UTF-8");
method.setRequestEntity(requestEntity);
httpClient.executeMethod(method);
ret= method.getResponseBodyAsString();
System.out.println(ret);
} catch (HttpException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (method != null) {
method.releaseConnection();
}
return ret;
}
}


有篇关于连接关闭的

http://seanhe.iteye.com/blog/234759

猜你喜欢

转载自blog.csdn.net/changliangwl/article/details/79158702