簡體   English   中英

如何使用Java讀取和發布到遠程服務器

[英]How to Read from and Post to a Remote Server using Java

我是這類問題的新手。 在這里,我想向網站API發出請求,並以JSON格式獲取響應。

然后,我想將此響應直接發送到其他遠程URL。

請參閱下面的示例代碼

    PostMethod post = new PostMethod("Your URL");

    post.setRequestBody("your json data");
    post.setRequestHeader("Content-type", "application/json;charset=utf-8");

    // Get HTTP client
    HttpClient httpclient = new HttpClient();
    // Execute request
    try
    {
        int result = httpclient.executeMethod(post);

        s_log.info("Response status code: " + result);
        s_log.info(post.getResponseBodyAsString());

    }
    catch (HttpException e)
    {
        e.printStackTrace();
    }
    catch (IOException e)
    {
        e.printStackTrace();
    }
    finally
    {

        post.releaseConnection();
    }

可以使用標准Java API完成對遠程URL的讀取和寫入,有關詳細信息,請參見官方Java教程:

https://docs.oracle.com/javase/tutorial/networking/urls/readingWriting.html

讀:

import java.net.*;
import java.io.*;

public class URLConnectionReader {
    public static void main(String[] args) throws Exception {
        URL oracle = new URL("http://www.oracle.com/");
        URLConnection yc = oracle.openConnection();
        BufferedReader in = new BufferedReader(new InputStreamReader(
                                    yc.getInputStream()));
        String inputLine;
        while ((inputLine = in.readLine()) != null) 
            System.out.println(inputLine);
        in.close();
    }
}

寫作

import java.io.*;
import java.net.*;

public class Reverse {
    public static void main(String[] args) throws Exception {

        if (args.length != 2) {
            System.err.println("Usage:  java Reverse "
                + "http://<location of your servlet/script>"
                + " string_to_reverse");
            System.exit(1);
        }

        String stringToReverse = URLEncoder.encode(args[1], "UTF-8");

        URL url = new URL(args[0]);
        URLConnection connection = url.openConnection();
        connection.setDoOutput(true);

        OutputStreamWriter out = new OutputStreamWriter(
                                         connection.getOutputStream());
        out.write("string=" + stringToReverse);
        out.close();

        BufferedReader in = new BufferedReader(
                                    new InputStreamReader(
                                    connection.getInputStream()));
        String decodedString;
        while ((decodedString = in.readLine()) != null) {
            System.out.println(decodedString);
        }
        in.close();
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM