我正在将应用升级到org.apache.http不推荐使用的API 23 .
我当前(已弃用)的代码如下所示:
HttpClient httpClient = new DefaultHttpClient();
File file = new File(attr.Value);
String url = server_url;
HttpPost request = new HttpPost(url);
FileEntity fileEntity = new FileEntity(file, "image/png");
request.setEntity(fileEntity);
HttpResponse response = httpClient.execute(request);
String output = getContent(response.getEntity().getContent());
Run Code Online (Sandbox Code Playgroud)
我已经找到了一些关于如何使用它的建议HttpURLConnection,但它们比当前的解决方案(不能再使用)复杂得多.我正在谈论用于执行与上述相同功能的许多代码行.
有没有人有一个很好的固定更短的解决方案呢?
java android httpurlconnection apache-commons-httpclient android-6.0-marshmallow
在我的项目中,我有以下项目结构:
我有一个生成war文件的模块,可以部署在Tomcat应用程序服务器中.该模块依赖于Axis2库:
<dependency>
<groupId>org.apache.axis2</groupId>
<artifactId>axis2</artifactId>
</dependency>
<dependency>
<groupId>org.apache.axis2</groupId>
<artifactId>axis2-transport-http</artifactId>
</dependency>
<dependency>
<groupId>org.apache.axis2</groupId>
<artifactId>axis2-webapp</artifactId>
<type>war</type>
</dependency>
Run Code Online (Sandbox Code Playgroud)
此类包含WEB-INF下conf文件夹中的axis2.xml文件.
现在这个模块依赖于一个单元模块,它具有jar的包类型.
现在在我的web模块中,在我的存根的代码中,我有以下代码:
.GazelleObjectValidator.getInstance()validateObject();
XcpdValidationService是jar模块(依赖项)中的一个类,此方法通过SSL调用外部Web服务并使用代理.
此Web服务客户端由JAX WS RI生成
但是这个类不使用父模块中的axis2.xml配置并使用它自己的轴配置,这是默认设置,我的代理没有配置...
@WebEndpoint(name = "GazelleObjectValidatorPort")
public GazelleObjectValidator getGazelleObjectValidatorPort() {
return super.getPort(new QName("http://ws.validator.sch.gazelle.ihe.net/", "GazelleObjectValidatorPort"), GazelleObjectValidator.class);
}
Run Code Online (Sandbox Code Playgroud)
该方法本身如下所示:
@WebMethod
@WebResult(name = "validationResult", targetNamespace = "")
@RequestWrapper(localName = "validateObject", targetNamespace = "http://ws.validator.sch.gazelle.ihe.net/", className = "net.ihe.gazelle.schematron.ValidateObject")
@ResponseWrapper(localName = "validateObjectResponse", targetNamespace = "http://ws.validator.sch.gazelle.ihe.net/", className = "net.ihe.gazelle.schematron.ValidateObjectResponse")
public String validateObject(
@WebParam(name = "base64ObjectToValidate", targetNamespace = "")
String base64ObjectToValidate,
@WebParam(name = "xmlReferencedStandard", targetNamespace = "") …Run Code Online (Sandbox Code Playgroud) 我正在与期望POST参数并期望Request body的Web服务进行通信.我已经确认可以使用我的REST控制台完成这样的POST请求,但是我无法使用Apache库在Java中发出这样的请求.
在下面的代码中,我能够POST到Web服务,它正确地接收变量raw_body的内容.如果我取消注释两个注释行中的第一行,则Web服务会收到"fname"参数,但它不再接收POST的正文.
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
...
HttpClient httpClient = new HttpClient();
String urlStr = "http://localhost:8080/MyRestWebService/save";
PostMethod method = new PostMethod(urlStr);
String raw_body = "This is a very long string, much too long to be just another parameter";
RequestEntity re = new StringRequestEntity(raw_body, "text/xml", "UTF-16");
//method.addParameter("fname", "test.txt");
//httpClient.getParams().setParameter("fname", "test.txt");
method.setRequestEntity(re);
Run Code Online (Sandbox Code Playgroud)
如何传输参数和身体?
我正在测试通过API的Java客户端将文件上传到CKAN/datahub.io上的数据集.
public String uploadFile()
throws CKANException {
String returned_json = this._connection.MultiPartPost("", "");
System.out.println("r: " + returned_json);
return returned_json;
}
Run Code Online (Sandbox Code Playgroud)
和
protected String MultiPartPost(String path, String data)
throws CKANException {
URL url = null;
try {
url = new URL(this.m_host + ":" + this.m_port + path);
} catch (MalformedURLException mue) {
System.err.println(mue);
return null;
}
String body = "";
HttpClient httpclient = new DefaultHttpClient();
try {
String fileName = "D:\\test.jpg";
FileBody bin = new FileBody(new File(fileName),"image/jpeg");
StringBody comment = new StringBody("Filename: …Run Code Online (Sandbox Code Playgroud) 有一个api我需要执行没有长度的八位字节流.它只是一个实时数据流.我遇到的问题是,当我提出请求时,它似乎试图在将信息读入输入流之前等待内容的结束,但是它没有看到内容的结束和具有NoHttpResponse异常的超时.以下是我的代码的简化版本:
private static HttpPost getPostRequest() {
// Build uri
URI uri = new URIBuilder()
.setScheme("https")
.setHost(entity.getStreamUrl())
.setPath("/")
.build();
// Create http http
HttpPost httpPost = new HttpPost(uri);
String nvpsStr = "";
Object myArray[] = nvps.toArray();
for(int i = 0; i < myArray.length; i ++) {
nvpsStr += myArray[i].toString();
if(i < myArray.length - 1) {
nvpsStr += "&";
}
}
// Build http payload
String request = nvpsStr + scv + streamRequest + "\n\n";
// Attach http data
httpPost.setEntity(new StringEntity(URLEncoder.encode(request,"UTF-8")));
return …Run Code Online (Sandbox Code Playgroud) java httpclient apache-commons-httpclient apache-httpclient-4.x
我是否知道如何使用"Transfer-Encoding:chunked"处理/读取响应?
目前我正在使用common-httpclient.3.1
我目前的编码如下(只能处理标题中内容长度的响应): -
httppost = new PostMethod(localurl);
httppost.setRequestHeader("Content-Type", "application/xml; charset=utf-8");
RequestEntity entity = new StringRequestEntity(in, "application/xml", "UTF-8");
httppost.setRequestHeader("Content-length", entity.getContentLength()+"");
httppost.setRequestEntity(entity);
for (int i=0; i<retryAttempt; i++) {
try {
httpclient.executeMethod(httppost);
if (httppost.getStatusCode() == 200) {
br = new BufferedReader(new InputStreamReader(httppost.getResponseBodyAsStream(), httppost.getResponseCharSet()));
String reply = null;
long len = httppost.getResponseContentLength();
if(len != 0) {
char[] cbuf = new char[Integer.parseInt(len+"")];
if (br.read(cbuf, 0, Integer.parseInt(len+"")) != -1 ) {
repOut = String.valueOf(cbuf);
}
}else{
while ((reply = br.readLine()) != null) {
if (!reply.equals("")) …Run Code Online (Sandbox Code Playgroud) 我正在使用Kerberos身份验证编写HTTP连接.我有"HTTP/1.1 401 Unauthorized".你能推荐我应该检查一下吗?我认为有一些想法,但我没有看到它.
可能是我应该用"Negotiate"设置标题"WWW-Authenticate"?
非常感谢您提供任何帮助和想法.
public class ClientKerberosAuthentication {
public static void main(String[] args) throws Exception {
System.setProperty("java.security.auth.login.config", "login.conf");
System.setProperty("java.security.krb5.conf", "krb5.conf");
System.setProperty("sun.security.krb5.debug", "true");
System.setProperty("javax.security.auth.useSubjectCredsOnly","false");
DefaultHttpClient httpclient = new DefaultHttpClient();
try {
NegotiateSchemeFactory nsf = new NegotiateSchemeFactory();
httpclient.getAuthSchemes().register(AuthPolicy.SPNEGO, nsf);
List<String> authpref = new ArrayList<String>();
authpref.add(AuthPolicy.BASIC);
authpref.add(AuthPolicy.SPNEGO);
httpclient.getParams().setParameter(AuthPNames.PROXY_AUTH_PREF, authpref);
httpclient.getCredentialsProvider().setCredentials(
new AuthScope(null, -1, AuthScope.ANY_REALM, AuthPolicy.SPNEGO),
new UsernamePasswordCredentials("myuser", "mypass"));
System.out.println("----------------------------------------");
HttpUriRequest request = new HttpGet("http://localhost:8084/web-app/webdav/213/_test.docx");
HttpResponse response = httpclient.execute(request);
HttpEntity entity = response.getEntity();
System.out.println("----------------------------------------");
System.out.println(response.getStatusLine());
System.out.println("----------------------------------------");
if (entity != null) {
System.out.println(EntityUtils.toString(entity));
} …Run Code Online (Sandbox Code Playgroud) 我在这里找到了一些关于如何下载文件的例子,但是大多数文件似乎都在使用HttpURLConnection.是否可以使用HttpClient下载文件?
我正在尝试使用HttpClient将文件上传/删除到webdav服务器.但是,只要文件名由空格组成,就没有任何工作.我收到一条错误消息"无效的URI ---转义的绝对路径无效".
这个我的URL ="http:// localhost:8080/test file.txt"
private boolean delete(String fileName) {
HttpClient client = new HttpClient();
HttpHost host = new HttpHost(WEBDAV_URL, PORT_NUMBER);
client.getHostConfiguration().setHost(host);
DeleteMethod del = new DeleteMethod(WEBDAV_URL_COMPLETE + fileName);
try {
client.executeMethod(del);
return true;
} catch (HttpException e) {
e.printStackTrace();
return false;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
Run Code Online (Sandbox Code Playgroud)
我应该使用任何方法或URL解析来解决问题
谢谢
编辑,通过用" %20 " 替换空格来找到解决方案.
**
URL.replaceAll("","%20")
**
我在pom.xml的依赖项部分添加了以下内容:
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.4.1</version>
<scope>test</scope>
</dependency>
Run Code Online (Sandbox Code Playgroud)
但是当我添加第一行的"快速入门指南"(http://hc.apache.org/httpcomponents-client-4.4.x/quickstart.html)时:
CloseableHttpClient httpclient = HttpClients.createDefault();
Run Code Online (Sandbox Code Playgroud)
IntelliJ IDEA突出显示"HttpClients"并告诉我:
无法解析符号'HttpClients'
看起来我配置有误.究竟出了什么问题?请告知如何在项目中添加对HttpClients的支持?
谢谢!
PS学到了一点,看起来""对于这种情况来说是多余的和错误的,我删除它但是没有帮助:仍然是不可编译的.
编辑:如果我将光标放到'HttpClients'并点击"Alt-enter"弹出窗口不包含任何要导入的类.看截图:

java classpath intellij-idea maven apache-commons-httpclient