【问题标题】:Java post xml file to url with authenticationJava将xml文件发布到带有身份验证的url
【发布时间】:2013-01-08 20:49:23
【问题描述】:

我目前使用下面的 Linux Shell 脚本

shell_exec("wget --output-document=/var/www/html/kannel/rresults/".$file.".res --post-file=/var/www/html/kannel/rbilling/".$file." --http-user=user1 --http-password=pass1 --header=\"Content-Type: text/xml\" 77.203.65.164:6011");

这个shell脚本使用来自linux的wget来执行带有基本认证的url并上传一个文件。

我想把它转换成java,这样它就可以了:

  1. 连接
  2. 认证
  3. 发布 XML 文件

另外,是否可以进行一次身份验证,然后发布任意数量的文件?

更新........ 我尝试了下面的代码

public class URLUploader {



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

    URL url = new URL("http://77.203.65.164:6011");
URLConnection conn = url.openConnection();
conn.setDoOutput(true);

String name = "user";
        String password = "password";

        String authString = name + ":" + password;
        System.out.println("auth string: " + authString);
        byte[] authEncBytes = Base64.encodeBase64(authString.getBytes());
        String authStringEnc = new String(authEncBytes);
        System.out.println("Base64 encoded auth string: " + authStringEnc);

conn.setRequestProperty("Authorization", "Basic " + authStringEnc);
OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());

writer.write("/var/www/html/kannel/javacode/13569595024298.xml");
writer.flush();
String line;
BufferedReader reader = new BufferedReader(new    InputStreamReader(conn.getInputStream()));
while ((line = reader.readLine()) != null) {
  System.out.println(line);
}
writer.close();
reader.close();

}
}

我试过上面的代码出错了:

身份验证字符串:optiweb:optiweb Base64 编码的身份验证字符串:b3B0aXdlYjpvcHRpd2Vi 线程“主”java.io.IOException 中的异常:服务器返回 HTTP 响应代码:500 用于 URL:77.203.65.164:6011 在 sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1403) 在 URLUploader.main(URLUploader.java:32)

有什么问题?

【问题讨论】:

  • 你是强调认证一次还是每次认证都可以?
  • 我希望它验证一次,然后是多个帖子和回复。

标签: java linux file shell


【解决方案1】:

您可以为此使用Apache HttpComponents

Here's an example for client authentication

package org.apache.http.examples.client;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

/**
 * A simple example that uses HttpClient to execute an HTTP request against
 * a target site that requires user authentication.
 */
public class ClientAuthentication {

    public static void main(String[] args) throws Exception {
        DefaultHttpClient httpclient = new DefaultHttpClient();
        try {
            httpclient.getCredentialsProvider().setCredentials(
                    new AuthScope("localhost", 443),
                    new UsernamePasswordCredentials("username", "password"));

            HttpGet httpget = new HttpGet("https://localhost/protected");

            System.out.println("executing request" + httpget.getRequestLine());
            HttpResponse response = httpclient.execute(httpget);
            HttpEntity entity = response.getEntity();

            System.out.println("----------------------------------------");
            System.out.println(response.getStatusLine());
            if (entity != null) {
                System.out.println("Response content length: " + entity.getContentLength());
            }
            EntityUtils.consume(entity);
        } finally {
            // When HttpClient instance is no longer needed,
            // shut down the connection manager to ensure
            // immediate deallocation of all system resources
            httpclient.getConnectionManager().shutdown();
        }
    }
}

Here's an example that does an upload

public void testUpload() throws Exception {
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost(myUploadUrl);

    MultipartEntity reqEntity = new MultipartEntity(
        HttpMultipartMode.BROWSER_COMPATIBLE);

    reqEntity.addPart("string_field",
        new StringBody("field value"));

    FileBody bin = new FileBody(
        new File("/foo/bar/test.png"));
    reqEntity.addPart("attachment_field", bin );

    httppost.setEntity(reqEntity);

    System.out.println("executing request " + httppost.getRequestLine());
    HttpResponse response = httpclient.execute(httppost);
    HttpEntity resEntity = response.getEntity();

    if (resEntity != null) {
        String page = EntityUtils.toString(resEntity);
        System.out.println("PAGE :" + page);
    }
}

【讨论】:

    【解决方案2】:

    您需要在请求中提供正确的 http 基本身份验证标头。在 Java 中,您可以通过编码 username:password 并将它们与您的请求一起传递来实现:

    URL url = new URL(urlString);
    URLConnection conn = url.openConnection();
    conn.setDoOutput(true);
    conn.setRequestProperty ("Authorization", Base64.encode(username+":"+password));
    
    OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
    
    writer.write(data);
    writer.flush();
    String line;
    BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    while ((line = reader.readLine()) != null) {
      System.out.println(line);
    }
    writer.close();
    reader.close();
    

    其中“数据”包含您要发布到服务器的内容。

    【讨论】:

    • 它也可以是 http digest auth,所以你的答案只适用于 http basic auth。 wget 支持这两种身份验证方法。
    • 嗨,我可以使用这个:writer.write("/var/www/html/newfile.xml"); ?这行得通吗
    • 不,那只会发布字符串“/var/www/html/newfile.xml”。您需要做的是读取文件(通过 FileInputReader 或类似的东西)并发布。
    • 读入一个字节数组并使用它?我知道我听起来很懒,但你能帮我把这部分添加到你的代码示例中吗?
    猜你喜欢
    • 1970-01-01
    • 2019-01-22
    • 2020-07-10
    • 2017-10-29
    • 1970-01-01
    • 1970-01-01
    • 2023-04-11
    • 2018-11-21
    • 2016-05-13
    相关资源
    最近更新 更多