本文主要是介绍Web后端http请求(带用户名和密码防止401 Unauthorized),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
Java
Java这方面的Jar包应该比较多,比如HttpClient,我这里使用最基本的:
使用代理的方式是在打开Http连接的时候同时传递一个Proxy参数。如果需要验证信息的话我们可以添加一个Http头参数来实现。
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.junit.Test;
import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;
public class TestVidyo {
@Test
public void downLoad() {
DefaultHttpClient httpClient = new DefaultHttpClient();
OutputStream out = null;
InputStream in = null;
String localFileName = "";
String url = "http://****.com.cn/replay/downloadRecording.do?file=680f1d0d-3251-4948-b7bb-975d6e2cf1e3"; // filelink
String username = "super";
String password = "password";
try {
HttpGet httpGet = new HttpGet(url);
String auth = "Basic " + Base64.encode((username + ":" + password).getBytes());
httpGet.addHeader("Authorization", auth);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity entity = httpResponse.getEntity();
in = entity.getContent();
long length = entity.getContentLength();
if (length <= 0) {
System.out.println("下载文件不存在!");
return;
}
File file = new File(localFileName);
if(!file.exists()){
file.createNewFile();
}
out = new FileOutputStream(file);
byte[] buffer = new byte[4096];
int readLength = 0;
while ((readLength=in.read(buffer)) > 0) {
byte[] bytes = new byte[readLength];
System.arraycopy(buffer, 0, bytes, 0, readLength);
out.write(bytes);
}
out.flush();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}finally{
try {
if(in != null){
in.close();
}
} catch (IOException e) {
e.printStackTrace();
}
try {
if(out != null){
out.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
为了大家清楚的知道引用的jar包,import一同奉上。本编博客是结合各方高手贴总结后的,也是经过本人测试成功后才发布的。相应jar包在csdn可以下载
其中的Base64.encode(user:password)是指把用户名和密码用冒号连接起来之后使用Base64编码后的值作为值的一部分。
通过这种方式只影响特定的Http连接,但是需要对代码进行修改。这种方式下是否可以使用Authenticator还未做验证。
这篇关于Web后端http请求(带用户名和密码防止401 Unauthorized)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!