0

我目前使用下面的 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 脚本使用wget来自 linux 的基本身份验证执行 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();

}
}

i tried the code above go the error:

auth string: optiweb:optiweb Base64 encoded auth string: b3B0aXdlYjpvcHRpd2Vi Exception in thread "main" java.io.IOException: Server returned HTTP response code: 500 for URL: 77.203.65.164:6011 at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1403) at URLUploader.main(URLUploader.java:32)

有什么问题?

4

2 回答 2

1

您可以为此使用Apache HttpComponents

这是客户端身份验证的示例

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();
        }
    }
}

这是一个上传的例子

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);
    }
}
于 2013-01-08T20:54:30.150 回答
0

您需要在请求中提供正确的 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();

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

于 2013-01-08T20:56:25.767 回答