LoginSignup
0
0

More than 1 year has passed since last update.

cscの作法 その259

Posted at

概要

cscの作法、調べてみた。
練習問題やってみた。

練習問題

httpプロトコルでエラーレスポンスを獲れ。

方針

  • webclient使う
  • try-catch使う
  • Response使う

サンプルコード

using System.Collections;
using System.IO;
using System;
using System.Text;
using System.Net;

namespace app
{
	class test0 {
		static void Main() {
			ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
			WebClient wc = new WebClient();
			string json = "{}";
			try
			{
				wc.Headers[HttpRequestHeader.ContentType] = "application/jose+json";
				//wc.Headers[HttpRequestHeader.ContentType] = "application/json";
				string response = wc.UploadString("https://acme-staging-v02.api.letsencrypt.org/acme/new-acct", "POST", json);
				Console.WriteLine(response);
			}
			catch (System.Net.WebException ex)
			{
				if (ex.Status == System.Net.WebExceptionStatus.ProtocolError)
				{
					System.Net.HttpWebResponse errres = (System.Net.HttpWebResponse) ex.Response;
					Console.WriteLine("{0}: {1}", errres.StatusCode, errres.StatusDescription);
					Console.WriteLine(ex.ToString());
					string responseText;
					using (var reader = new StreamReader(ex.Response.GetResponseStream()))
					{
						responseText = reader.ReadToEnd();
					}
					Console.WriteLine("WebException caught. Response text is {0}", responseText);
				}
				else
					Console.WriteLine(ex.Message);
			}
		}
	}
}

実行結果

>res0
BadRequest: Bad Request
System.Net.WebException: リモート サーバーがエラーを返しました: (400) 要求が不適切です
   場所 System.Net.WebClient.UploadDataInternal(Uri address, String method, Byte[] data, WebRequest& request)
   場所 System.Net.WebClient.UploadString(Uri address, String method, String data)
   場所 app.test0.Main()
WebException caught. Response text is {
  "type": "urn:ietf:params:acme:error:malformed",
  "detail": "Parse error reading JWS",
  "status": 400
}

>

以上。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0